有条件地执行从参数中传入的代码。

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

我尝试了以下内容:

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'

然而,它似乎不起作用。即使我错误格式化字符串以引起语法错误,什么也没有发生。

我在尝试着做一些不可能实现的事情吗?

点赞
用户1009479
用户1009479

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

local func = loadstring(CodeIfA);
func();
2014-02-04 08:04:46
用户1190388
用户1190388

loadstring 返回函数实例。你需要从你的函数返回 loadstring 的执行结果:

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

然后在外部调用它:

local temp = PrintCondition(
    [[
        print("global is A");
    ]],
    [[
        print("global is B");
    ]]
)
temp()
2014-02-04 08:04:56