lua通过loadstring实现eval和lambdal表达式

本文详细解析了如何使用Lua脚本语言将字符串形式的Lambda表达式转换为可执行函数,包括验证字符串中是否只包含一个冒号、确保输入类型为字符串或数字、并正确分割参数和表达式部分。
function eval(str)
if type(str) == "string" then
return loadstring("return " .. str)()
elseif type(str) == "number" then
return loadstring("return " .. tostring(str))()
else
error("is not a string")
end
end

function lambda(lambda_string,...)
--验证是否仅存在一个:号
pos = string.find(lambda_string,":")
if pos ~= nil then
if string.find(lambda_string,":",pos+1)~= nil then
error('more than one ":"')
end
end
if type(lambda_string) ~= "string" then
error("is not a string")
end
--lambda x:x+x 将其分割为 参数 x 和 表达式 x+x 的形式
parameter = string.sub(lambda_string,1,pos-1)
expression = string.sub(lambda_string,pos+1,-1)

fun = string.format("return function(%s) return %s end",parameter,expression)
local func = loadstring(fun)()(...)
return func
end
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值