以编程方式创建本地变量(在 Lua 中)

我一直在用 Lua 中的自制文档系统玩耍。例如:

fun("abs","返回绝对值", function (x,y)
        return math.abs(x,y) end)

我卡在了一个细节上。我想将“abs”作为一个本地函数。但是我不知道如何以编程方式实现。

当然,我可以写入某个 Lib 对象的字段并调用它 Lib.abs(x,y) ,我认为我将不得不这样做。有没有聪明的 Lua 专家告诉我如何避免这样做呢?

点赞
用户1442917
用户1442917

我认为你没有很多选择,因为虽然可以将值分配给一个本地变量(使用 debug.setlocal 函数),但它是通过索引而不是名称来分配的,因此这个索引必须已经存在一个本地变量。

我认为你的建议将函数存储在一个表字段中没有任何问题。

2021-08-05 02:39:18
用户14091631
用户14091631

我会做的是,我会编写(甚至覆盖)_G,运行你的函数/程序,然后再恢复它。

function callSandboxed(newGlobals, func)
    local oldGlobals = {} --make a new table to store the values to be writen (to make sure we don't lose any values)
    for i,_ in pairs(newGlobals) do
        table.insert(oldGlobals, _G[i]) --Store the old values
        _G[i] = newGlobals[i] --Write the new ones
    end
    func() --Call your function/program with the new globals
    for i,v in pairs(oldGlobals) do
        _G[i] = v --Restore everything
    end
end

在这种情况下,你想做的是:

--Paste the callSandboxed function

callSandboxed({abs=math.abs},function()print(abs(-1))end) --Prints 1

如果您想要从_G中删除所有旧值(不仅仅是要替换的值),那么您可以使用以下代码:

function betterCallSandboxed(newGlobals, func) --There's no point deep copying now, we will replace the whole table
    local oldGlobals = _G --Make a new table to store the values to be writen (to make sure we don't lose any values)
    _G = newGlobals --Replace it with the new one
    func() --Call your function/program with the new globals
    _G = oldGlobals
end

现在,在func内部,printmath等内容为nil。

2021-08-07 17:35:36