Skip to content

Commit 52e1e14

Browse files
committed
ipairs_clone
1 parent 55724f1 commit 52e1e14

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
local res_type = world.get_type_by_name("TestResourceWithVariousFields")
2+
local res = world.get_resource(res_type)
3+
4+
local iterated_vals = {}
5+
for i, v in res.vec_usize:ipairs_clone() do
6+
assert(i == #iterated_vals + 1, "Index mismatch: expected " .. (#iterated_vals + 1) .. ", got " .. i)
7+
iterated_vals[#iterated_vals + 1] = v
8+
end
9+
10+
assert(#iterated_vals == 5, "Length is not 5")
11+
assert(iterated_vals[1] == 1, "First value is not 1")
12+
assert(iterated_vals[2] == 2, "Second value is not 2")
13+
assert(iterated_vals[3] == 3, "Third value is not 3")
14+
assert(iterated_vals[4] == 4, "Fourth value is not 4")
15+
assert(iterated_vals[5] == 5, "Fifth value is not 5")

crates/languages/bevy_mod_scripting_lua/src/bindings/reference.rs

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -392,6 +392,50 @@ impl UserData for LuaReflectReference {
392392
}
393393
});
394394

395+
m.add_method("ipairs_clone", |lua, s: &LuaReflectReference, _args: ()| {
396+
profiling::function_scope!("ipairs_clone");
397+
let world = ThreadWorldContainer
398+
.try_get_world()
399+
.map_err(IntoMluaError::to_lua_error)?;
400+
401+
let iter_func = world
402+
.lookup_function([TypeId::of::<ReflectReference>()], "iter_clone")
403+
.map_err(|f| {
404+
InteropError::missing_function(f, TypeId::of::<ReflectReference>().into())
405+
})
406+
.map_err(IntoMluaError::to_lua_error)?;
407+
408+
let result = iter_func
409+
.call(vec![ScriptValue::Reference(s.clone().into())], LUA_CALLER_CONTEXT)
410+
.map_err(IntoMluaError::to_lua_error)?;
411+
412+
match result {
413+
ScriptValue::FunctionMut(func) => {
414+
let mut index = 0i64;
415+
lua.create_function_mut(move |lua, _args: ()| {
416+
let result = func
417+
.call(vec![], LUA_CALLER_CONTEXT)
418+
.map_err(IntoMluaError::to_lua_error)?;
419+
420+
match result {
421+
ScriptValue::Unit => {
422+
// End of iteration
423+
Ok((mlua::Value::Nil, mlua::Value::Nil))
424+
}
425+
_ => {
426+
// Return (index, value) tuple for ipairs
427+
index += 1;
428+
let idx = mlua::Value::Integer(index);
429+
let val = LuaScriptValue(result).into_lua(lua)?;
430+
Ok((idx, val))
431+
}
432+
}
433+
})
434+
}
435+
_ => Err(mlua::Error::RuntimeError("iter_clone function did not return a FunctionMut".to_string()))
436+
}
437+
});
438+
395439
m.add_meta_function(MetaMethod::ToString, |_, self_: LuaReflectReference| {
396440
profiling::function_scope!("MetaMethod::ToString");
397441
let world = ThreadWorldContainer

0 commit comments

Comments
 (0)