A global variable named type hides the built-in type () function in Lua

The C ++ program I'm working on uses lua for customization. It installs several lua functions using a hard-coded script:

luaL_loadbuffer(pmLuaState, headerscript, strlen(headerscript), "header script");

Then it loads the configuration lua file (which calls the previously mentioned functions):

luaL_loadfile(pmLuaState, filename)

Unfortunately, the Lua configuration file uses a global variable called type, so trying to call the built-in type () function from my header with the Lua error:

attempt to call global 'type' (a string value)

Due to the limitations of my script, I cannot edit the configuration file in violation. I am wondering if there is a way to explain that I want to use the built-in type () function.

Lua, , , , ( , script).

Lua: 5.1.4

+3
2

, , .. script _G.type .

local type = type -- problem solved

. script .

local loadedmodules = {}
import = function(filename)
    if (loadedmodules[filename]) then
        return loadedmodules[filename]
    end
    local env = {}
    local func = loadfile(filename);
    local envmeta = {
        __index = _G -- changed thanks to comments
    }
    setmetatable(env, envmeta) -- Allow the imported script to read only our globals
    setfenv(func, env) -- set func _G to env
    func() -- Load the script
    return loadedmodules[filename] = env -- Set the result and return it.
end

++ , .

script Lua, ++ . Lua ++, API .

+3

sandbox , .

lua_setfenv() , luaL_load*().

: , metatables.

Lua:

setfenv(chunk, setmetatable({__index = _G }))

( , , C.)

, . , config , table.concat = myevilfunction. . Wiki, ( ).

+3

Source: https://habr.com/ru/post/1789841/


All Articles