简体   繁体   中英

Getting variables from a file

Supposed I have a "test.lua" file like this:

myVar = 5

Food = function()

end

If I load the file via loadfile or via Lua API (in C++ or whatever) and run it, the variables will be saved under the global namespace _G; however, I'd like to have them separately, like _test.myVar and _G.myVar. (The reason for this is that I want to have a list of the variables from that file only). Thanks.

运行脚本之前,请使用lua_setfenv

module('_test')

myVar = 5

Food = function()

end

Then, from some other file:

require 'test.lua' --> or loadfile('test.lua')()

print(myVar) --> nil
print(Food) --> nil
print(_test.myVar) --> 5
print(_test.Food) --> function

What lhf said.

For additional robustness in the face of files that may not be from a completely trusted source, you should read about sandboxing at the wiki.

The key idea is to be careful about what global functions and variables are available to code executing in the context of your data file. An easy way to get a lot of control over that is to construct the environment table that supplies the globals to the script so that it only contains a white list of safe functions. You do this by constructing a suitable table, and then setting it as the environment of the freshly compiled script before calling it. lua_setfenv() from the C API or setfenv from the Lua side can both be used on the object returned by a successful call to luaL_loadfile() , loadfile or one of their relatives in either the C API or from Lua, respectively. Once the script is loaded and the environment assigned, the you run it with lua_pcall() or pcall .

Don't forget to check everything for errors.

When the script completes, variables it created have been written or updated in its environment table, rather than _G .

Naturally, that environment table could use a metatable to make some of the globals you supply the script effectively read-only as well.

For additional control, some have taken the idea further and arranged to limit the number of virtual instruction cycles or real clock time allowed for the script to run. It is even possible to inspect the bytecode after loading for certain opcodes. That can be used to prevent even attempting to execute a script that contains a loop in many cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM