Lua 提供 loadstring (5.1) / load (5.2+) 將字符串編譯為函數並執行,類似 JavaScript 的 eval()。本文演示兩大核心場景:計算字符串數學表達式與動態執行任意代碼片段。
local param = "7*100"
-- 關鍵:在字符串前加 "return ",使其成為返回表達式的函數體
local func = loadstring("return " .. param)
local result = func()
print(result) -- 700
原理:loadstring 編譯字符串為無參函數,調用該函數執行代碼並返回 return 的值。
-- 直接執行
loadstring("print('hello')")()
-- 或分步:編譯 -> 調用
local funcStr = "print('test')"
local func = loadstring(funcStr)
func() -- 輸出: test
-- 模擬從服務器獲取代碼字符串
local remoteCode = [[
local function updateResources()
print("Updating resources...")
-- 實際業務邏輯
end
updateResources()
]]
-- 安全載入並執行
local ok, err = pcall(function()
local f = assert(loadstring(remoteCode))
f()
end)
if not ok then
print("Remote code execution failed:", err)
end
os、io、debug 等危險庫,設置 setfenv 限制全局表)。load 支持 env 參數直接指定環境表,更安全。| 版本 | 函數 | 簽名 |
|---|---|---|
| Lua 5.1 | loadstring | loadstring(string [, chunkname]) |
| Lua 5.2+ | load | load(chunk, chunkname, mode, env) |
Lua 5.1 中 loadstring 等價於 load(string, chunkname, "t", _G)。
chunkname 參數用於錯誤堆棧顯示(如 "=remote_code"),方便定位動態代碼錯誤行。loadstring 返回 nil, error_msg,務必用 assert 或 pcall 捕獲。loadstring 賦予了 Lua 極強的動態性,配合沙箱機制,是插件系統、腳本化配置、熱更新的核心基石 —— 用之以度,慎之以安。