只是瞎搞在computercraft,試圖用一個函數作爲參數,但不能讓它的工作使用函數作爲變量,LUA
bla = function() print("bla") end
execfunc = function(func) func() end
execfunc(bla())
我想做些事情由上述可見,但隨着工作的代碼而不是這個廢話
只是瞎搞在computercraft,試圖用一個函數作爲參數,但不能讓它的工作使用函數作爲變量,LUA
bla = function() print("bla") end
execfunc = function(func) func() end
execfunc(bla())
我想做些事情由上述可見,但隨着工作的代碼而不是這個廢話
從參數中刪除()
到execfunc
。您想通過bla
至execfunc
而不是致電bla()
的結果。
> bla = function() return "bla" end
> execfunc = function(func) print(type(func)) end
> execfunc(bla())
string
> execfunc(bla)
function
你這樣做是正確的形式參數方面:使用函數調用操作()
上表達func
。如果表達式的值實際上是一個函數,它將被調用;如果不是,Lua會拋出一個錯誤。
在實際的論證方面,你有一個錯誤。要傳遞參數,只需在參數列表中添加一個表達式即可。您想要將變量bla
中的值傳遞到execfunc(bla)
。表達式只是一個變量,而變量中的值是一個函數值,這一事實不會改變任何事實。
Lua變量是動態類型的。編譯器不會跟蹤哪些變量在使用之前會被最後賦予函數值。事實上,它不能。你可以寫一個函數,有時會返回一個函數,有時會返回一個數字。無論哪種情況,您仍然可以嘗試調用結果。
local f = function()
if Wednesday then
return 7
else
return function (n) return n + 1 end
end
end
local g = f()
g() -- is the value in g a function or not? It doesn't matter to the compiler.
,你得到你的函數原料,而不調用它的方式是不使用括號()
local function a()
print("AAA")
end
local function b(func)
func()
end
b(a)
-- Output:
-- AAA
,併爲您的情況:
...
execfunc(bla)
-- Everything was fine except the parenthesis for your function (bla)
很長一段時間了,不過,謝謝你非常,這有幫助 – user3837761 2014-10-16 18:32:31