开发者

"attempt to index global 'f' (a function value)" when trying to attach a function to the result of loadfile

开发者 https://www.devze.com 2023-03-30 12:28 出处:网络
The code says it all: #tryModA.lua: f,err=loadfile(\"tryModB.lua\") if not f then print(\"F is nil!!! Err:\"..err)

The code says it all:

#tryModA.lua:
f,err=loadfile("tryModB.lua")
if not f then
    print("F is nil!!! Err:"..err)
else
    f.fn=function (x)
        print("x="..x)
    end
    f()
end

And here is the loaded file:

#tryModB.lua:
fn("hello")

Error:

lua: tryModA.lua:7: attempt to index global 'f' (a function value)
stack traceback:
    tryModA.lua:7: in main chunk
    [C]: ?

Question: why does it happen ?

Isn't it true that loadfile() returns a functi开发者_运维知识库on object and I can attach another function to it? PS. I come from a JavaScript programming background where it has prototype-based objects. I assume Lua has the same prototype based objects.


In Lua, loadfile() returns a function (not a function object) and functions can only be called. "Attaching" whatever to a function like you are trying is not possible.

Now, Lua tables are completely different story and the prototype-based concepts from JavaScript probably apply to them (I'm not very familiar with JS). The simplest way to make your code work at this point is to make fn global i.e. replace f.fn = function... with fn = function... although this might not be what you want.

0

精彩评论

暂无评论...
验证码 换一张
取 消