0

I'm trying to use lua with my c++ program and when I look up for how to use multiple lua script with I found this result https://stackoverflow.com/a/61684333/22979136
I modified this result and eventualy end up with this

local file_env = {}
local file_chunk = {}

function AddScript(ScriptLocation, index, Nd)
    file_env[index] = setmetatable({}, {__index = _G})
    file_chunk[index] = loadfile(ScriptLocation)

    _ENV = file_env[index]

    file_chunk[index]()

    file_env[index].InitNode(Nd)
    file_env[index].Start()
end

function UpdateScript(index)
    print(file_env[index])
    file_env[index].Update()
end

but there is some issue
when I call the "UpdateScript" function in my c++ program I get no result and "print(file_env[index])" just gives me the "nill" result
how can I fix this?

I tried to call the "UpdateScript" function inside the "AddScript" function but that didnt seem to help

1
  • Can you please provide a minimal example of how you call these functions from C++ which results in this error? Commented Nov 24, 2023 at 21:17

1 Answer 1

1

In Lua, an environment is an internal property of a function.
So, replace

    file_chunk[index] = loadfile(ScriptLocation)

    _ENV = file_env[index]

with

    file_chunk[index] = loadfile(ScriptLocation, "t", file_env[index])

to embed environment into a function on its creation.
You will be unable to set this function's environment later.

Sign up to request clarification or add additional context in comments.

5 Comments

when i tried this and run the update function on my program the results were the same i think my problem is that this function does not set the tables in the script it only changes the value in the function and i dont know how to fix this
"You will be unable to set this function's environment later." You can, with the debug library: Recreating setfenv() in Lua 5.2
@JosephSible - Debug library is not helpful here. That solution doesn't work if Lua program is compiled to bytecode with debug info stripped (because upvalue names are stripped too, and you never know which one is the "_ENV")
@ESkri Don't chunks always only have one upvalue?
@JosephSible - Yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.