lua - 有条件地执行来自参数的代码

标签 lua

我正在尝试根据全局变量有条件地执行通过函数参数传入的一些代码块。

我尝试了以下方法:

function PrintCondition(CodeIfA, CodeIfB)
    if SomeGlobal == "A" then
        loadstring(CodeIfA);
        return true;
    elseif SomeGlobal == "B" then
        loadstring(CodeIfB);
        return true;
    else
        Error();
        return false;
    end
end

然后我调用该函数

local temp = PrintCondition(
    [[
        print("global is A");
    ]],
    [[
        print("global is B");
    ]]
);
print(temp); -- prints 'true'

但是,似乎不起作用。即使我错误地格式化字符串以引发语法错误,我也什么也得不到。

我是否正在尝试一些无法完成的事情?

最佳答案

所有loadstring()(或Lua 5.2中的load())所做的只是加载字符串,它并没有真正运行它,你需要保存它到一个函数然后运行它:

local func = loadstring(CodeIfA);
func();

关于lua - 有条件地执行来自参数的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21546835/

相关文章:

java - luabind 和 java

arrays - 展平 Lua 中的嵌套列表

types - Haxe lua.Table<字符串,整数> : String should be Int

python - Lua 作为通用脚本语言?

apache - lua 嵌入 html 与 apache

c++ - 如何将命名空间添加到 Lua?

function - Lua:冒号、 'self' 和函数定义与调用

c++ - Luabind: "No matching overload found, candidates:"

lua - 如何更改表键 - LUA langg

lua - Lua:什么时候可以使用冒号语法?