lua - 从字符串调用函数

时间:2012-10-16 11:10:21

标签: lua

从我在本网站上看到的内容,以下内容应该有效。 可以请一些善意的灵魂指出我出错的地方吗?

我在代码中嵌入了更多描述和打印返回,希望能够更轻松地阅读

local m = {
 {opt = "Solar Panels", cmd = "solarPanel"}
     -- There are many more options here.
}  

function doTheMenu()
 print("Welcome to Spyder's Factory")
 print("")
 print("What would you like to make?")
 local n = 1
 local l = #m - 1
 while true do             --This while loop may or may not be relevant to the question, it's the menu
 term.clear()              --this is ComputerCraft lua, the term function is defined
 term.setCursorPos(1,2)    --elsewhere in an API
  for i, j in pairs(m) do
   if i == n then
    if i < 10 then print(i, "  ["..j.opt.."]") else  print(i, " ["..j.opt.."]") end
     fsel = j.cmd          --set fsel to the function name I require in case of a break
     tsel = j.opt          --Ditto, tsel, human-friendly name
   else
    if i < 10 then print(i, "   "..j.opt) else  print(i, "  "..j.opt) end
   end
  end
  local a, b = os.pullEvent("key") 
  if b == 200 and n > 1 then n = n - 1 end
  if b == 208 and n <= l then n = n + 1 end 
  if b == 28 then break end
 end
 write("\nSure, how many "..tsel.."? ")
 qty = tonumber(read())
 req[fsel] = req[fsel] + qty
 str = fsel.."("..qty..")"
 print("Loading function '"..fsel.."("..qty..")'") --Returns "Loading function 'solarPanel(1)'"
 func = loadstring(str)
 print(func)      --Returns "function: 2cdfc5a7"
 print("Loading function")
 func()  --The error line, Returns "string:1: attempt to call nil"
 --tellUserWhatNeed()
 --makeItHappen()
end

doTheMenu()

问题是代码无法运行并出现错误:

string:1 attempt to call nil

2 个答案:

答案 0 :(得分:0)

另外什么是term变量,如果这是您的所有代码,term未定义且为null

那就是说:_G[fsel]nil还是fselnil

您确定在_G中声明了名称存储在fsel中的函数吗?

E.I。在问题专栏print (_G[fsel])之前调用,看看它给你的是什么。

答案 1 :(得分:0)

这是最终解决方案的解决方案:

local f = loadstring(str)
if f then
 setfenv(f, getfenv())
 f()
end

这取代了以上几行:

print("Loading function '"..fsel.."("..qty..")'") 
func = loadstring(str)
print(func)    
print("Loading function")
func() 

除了添加用于加载函数的基本错误处理