Skip to content

mlua and lua_setfenv integration #559

Answered by khvzak
bobbens asked this question in Q&A
Apr 19, 2025 · 1 comments · 7 replies
Discussion options

You must be logged in to vote

testfunc is a C function and lua.globals() will always be the thread (main) globals regardless of what you do via setfenv.
It's equivalent to

lua_pushvalue(L, LUA_GLOBALSINDEX);

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:

function a()
    print("a", global_var)
    b()
end

function b()
    print("b", global_var)
end

global_var = 10

setfenv(a, setmetatable({global_var = 20}, {__index = _G}))
a()

prints:

a	20
b	10

Replies: 1 comment 7 replies

Comment options

You must be logged in to vote
7 replies
@khvzak
Comment options

Answer selected by bobbens
@bobbens
Comment options

@khvzak
Comment options

@bobbens
Comment options

@bobbens
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants