gpt4 book ai didi

templates - Lua:将上下文传递到加载字符串中?

转载 作者:行者123 更新时间:2023-12-02 22:26:02 24 4
gpt4 key购买 nike

我试图将上下文传递到一个动态表达式中,我会评估 for 循环的每次迭代。我知道加载字符串仅在全局上下文中计算,这意味着局部变量不可访问。就我而言,为了字符串求值的目的,我通过将本地转换为全局来解决此限制。这是我所拥有的:

require 'cosmo'

model = { { player = "Cliff", age = 35, gender = "male" }, { player = "Ally", age = 36, gender = "female" }, { player = "Jasmine", age = 13, gender = "female" }, { player = "Lauren", age = 6.5, gender = "female" } }

values = { eval = function(args)
output = ''
condition = assert(loadstring('return ' .. args.condition))
for _, it in ipairs(model) do
each = it
if condition() then
output = output .. each.player .. ' age: ' .. each.age .. ' ' .. '\n'
end
end
return output
end }
template = "$eval{ condition = 'each.age < 30' }"

result = cosmo.fill(template, values)
print (result)

我的最终目标(除了掌握 Lua 之外)是构建一个类似 XSLT 的诱人引擎,我可以在其中执行以下操作:

apply_templates{ match = each.age > 30}[[<parent-player>$each.player</parent-player>]]

apply_templates{ match = each.age > 30}[[<child-player>$each.player</child-player>]]

...并生成不同的输出。目前,我仍坚持上述通过全局分享本地背景的鹰派方式。这里有人对我如何去做我想做的事情有更好的见解吗?

最佳答案

值得注意的是setfenv was removed from Lua 5.2 and loadstring is deprecated 。 5.2 是相当新的,因此您暂时不必担心它,但可以编写适用于这两个版本的加载例程:

local function load_code(code, environment)
if setfenv and loadstring then
local f = assert(loadstring(code))
setfenv(f,environment)
return f
else
return assert(load(code, nil,"t",environment))
end
end

local context = {}
context.string = string
context.table = table
-- etc. add libraries/functions that are safe for your application.
-- see: http://lua-users.org/wiki/SandBoxes
local condition = load_code("return " .. args.condition, context)

版本 5.2 load处理旧的 loadstring行为并设置环境(在您的示例中为上下文)。 5.2版本还改变了environments的概念,所以 loadstring 可能是您最不用担心的。尽管如此,还是值得考虑一下,这样可能会为自己节省一些工作。

关于templates - Lua:将上下文传递到加载字符串中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9268954/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com