Lua中能否将字符串转换为函数并通过其执行脚本?
Lua 实现方案
以下实现适配Lua 5.1版本,高版本Lua可将loadstring替换为load做兼容。
基础实现(满足核心需求)
核心逻辑为对字符串做自定义偏移编码,解码后从全局表中取出对应的loadstring函数,校验通过后执行目标脚本。
-- 编码函数:offset为自定义偏移量,可自行修改增强保密性 local function encode(str, offset) offset = offset or 5 local encoded_chars = {} for i = 1, #str do encoded_chars[i] = string.char(string.byte(str, i) + offset) end return table.concat(encoded_chars) end -- 解码函数:offset需要和编码时使用的数值一致 local function decode(encoded_str, offset) offset = offset or 5 local decoded_chars = {} for i = 1, #encoded_str do decoded_chars[i] = string.char(string.byte(encoded_str, i) - offset) end return table.concat(decoded_chars) end -- 业务逻辑 local encoded_val = encode("loadstring") local exec_func = _G[decode(encoded_val)] if exec_func == loadstring then -- loadstring返回函数,加括号执行 exec_func("print('Hello')")() end
完全匹配示例语法的实现
如果需要完全对齐你给出的示例调用结构,可以通过元表封装编码结果,实现直接调用变量执行脚本的效果:
local default_offset = 5 -- 解码方法复用 local function decode_str(encoded_str, offset) offset = offset or default_offset local decoded_chars = {} for i = 1, #encoded_str do decoded_chars[i] = string.char(string.byte(encoded_str, i) - offset) end return table.concat(decoded_chars) end -- 编码函数返回可调用对象 local function encode(str, offset) offset = offset or default_offset local encoded_chars = {} for i = 1, #str do encoded_chars[i] = string.char(string.byte(str, i) + offset) end local encode_obj = { content = table.concat(encoded_chars), offset = offset } -- 绑定__call元方法实现直接调用 setmetatable(encode_obj, { __call = function(self, code) local func = _G[decode_str(self.content, self.offset)] return func(code) end }) return encode_obj end -- 解码方法兼容对象入参 local function decode(encode_obj) return _G[decode_str(encode_obj.content, encode_obj.offset)] end -- 完全匹配你示例的写法 local var = encode("loadstring") if decode(var) == loadstring then var("print('Hello')")() end
注意事项
- 可以根据需求替换编码逻辑为Base64、对称加密等实现,只要保证解码后能还原出原始字符串
loadstring即可。 - 执行
loadstring返回的函数时如果需要传参,可以直接在调用括号内传入对应参数。
内容的提问来源于stack exchange,提问作者Beemo
相关产品推荐
相关产品推荐

