-
Hello, I'm still working on moving a large C codebase to mlua, and have hit a snag using environments in C with
I am using luajit. I assume I'm misunderstanding how the globals work in mlua vs lua5.1 C API? Is it possible to get them to play well together? |
Beta Was this translation helpful? Give feedback.
Answered by
khvzak
Apr 20, 2025
Replies: 1 comment 7 replies
-
I've made a minimal test case on the issue: fn main() -> mlua::Result<()> {
#[allow(non_snake_case)]
let L = unsafe{ mlua::ffi::luaL_newstate() };
let lua = unsafe { mlua::Lua::init_from_ptr( L ) };
unsafe {
mlua::ffi::luaopen_base( L );
}
let t = lua.create_table()?;
let m = lua.create_table()?;
m.set("__index", lua.globals())?;
t.set_metatable(Some(m));
t.set( "testfunc", lua.create_function( |lua, ()| {
let name: mlua::Value = lua.globals().get("__name")?;
dbg!(name);
Ok(())
})?)?;
t.set("__name", "foo" )?;
let rk = lua.create_registry_value( t )?;
lua.load("
function main ( str )
print( __name, str )
testfunc()
end
").exec()?;
unsafe {
mlua::ffi::lua_getglobal( L, c"main".as_ptr() );
mlua::ffi::lua_pushstring( L, c"hello world".as_ptr() );
mlua::ffi::lua_rawgeti( L, mlua::ffi::LUA_REGISTRYINDEX, rk.id().into() );
mlua::ffi::lua_setfenv( L, -3 );
if mlua::ffi::lua_pcall( L, 1, 0, 0 ) != 0{
dbg!( std::ffi::CStr::from_ptr( mlua::ffi::luaL_tolstring( L, -1, std::ptr::null_mut() ) ) );
}
}
Ok(())
} Which prints:
I would expect the last print to be the value of __name, but it is not. EDIT: Created repo at https://github.com/bobbens/mlua_setfenv_globals for easy testing. |
Beta Was this translation helpful? Give feedback.
7 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
testfunc
is a C function andlua.globals()
will always be the thread (main) globals regardless of what you do viasetfenv
.It's equivalent to
Another note, when you call a Lua function inside another Lua function with modified environment, inner function has own environment and does not inherit from caller (only from creator).
See:
prints: