因為loadstring總是在全局環境中編譯它的串,所以編譯出的函數訪問的變量是全局變量。為了避免污染全局環境我們需要用setfenv修改函數的環境
function eval(equation, variables) if(type(equation) == "string") then local eval = loadstring("return "..equation); if(type(eval) == "function") then setfenv(eval, variables or {}); return eval(); end end end
使用:
local str = "200+lv*10+growth*0.1"
local val = eval(str, {lv = 3, growth = 100})
print(val)--240
