1

根据我在本网站上阅读的内容,以下内容应该可以工作。可以请一些好心的人指出我要去哪里错了吗?

我在代码中嵌入了更多描述和打印返回,希望能更容易阅读

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
4

2 回答 2

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() 

以及添加用于加载函数的基本错误处理

于 2012-10-16T23:21:29.167 回答
0

还有什么是term变量,如果这就是你的所有代码,term没有定义并且是null

也就是说:要么_G[fsel]nil,要么fselnil

你确定你有在_G中声明的函数,名字存储在fsel中吗?

在问题行之前打电话print (_G[fsel]),看看它给了你什么。

于 2012-10-16T11:30:11.210 回答