Pregunta

I am trying to embed Lua into a game. What I want to do is to create a load function, which will load all files in a folder and then create objects based off those files which will be stored on the C++ side. However, if I use something like dofile, it pollutes everything with the variables that are in that file. How do I change this import to be local?

¿Fue útil?

Solución

You can use loadfile to get the function based on the file content, then setfenv(fn,{}) to set the environment, and then call that function (probably wrapped into pcall):

local fn, err = loadfile("myfile")
if fn then
  setfenv(fn,{})
  local ok, err = pcall(fn)
  if not ok then error(err) end
else
  error(err)
end

You can also populate the table you pass to setfenv with the values you need the script to have access to or provide access to the global environment with something like:

local env = {}
setmetatable(env,{__index = _G})
setfenv(fn,env)

This is all for Lua 5.1.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top