0

Im trying to save myself some headache in a project im working on by splitting it up in files but I cannot seem to be able to cross call functions. (inside file_a, call a function in file_b which calls a function in file_a)

Is this just not possible or am i doing it wrong?

file_a:

local imported = require("fileb")
m = imported:new(BC)
m.print_message("hi")

file_b:

class_b = {
    BC = {}
}

function class_b:print_message(message)
    print(message)
end

function class_b:new (BC)
    local AB = {} 
    AB = BC or {}
    AB._index = class_b
    setmetatable(AB, self)
    return AB
end
return class_b

When i run this i get: attempt to call nil value (field 'print_message')

My project is much larger and complex at the moment but i extracted the logic i am working with right now to show what im trying to do to be able to cross call the functions.

jmelger
  • 87
  • 5
  • This has nothing to do with files and Lua doesn't have classes. `m` does get to be a new table `{}` with the metatable set to `class_b`. But, what part of that means it should have a `print_message` function? Nothing gives `m` a `print_message` function, since it's not in the table `m` itself and there's no `__index` either. – user253751 Sep 29 '22 at 19:02
  • How could i go about being able to cross use functions? Right now pretty much im trying to have class_b add itself to BC which is passed as an argument to new() – jmelger Sep 29 '22 at 19:14
  • Lua doesn't look in the metatable the way you're thinking - it looks in `__index` in the metatable. So if you want it to find functions in `class_b` then you set the metatable to some table whose `__index` is `class_b` – user253751 Sep 29 '22 at 19:16
  • I edited how i've got it right now. Its still not working tho, could you elaborate? – jmelger Sep 29 '22 at 19:23
  • Tell me: What is the __index of AB's metatable? – user253751 Sep 29 '22 at 19:27
  • AB._index = class_b – jmelger Sep 29 '22 at 19:30
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/248455/discussion-between-jmelger-and-user253751). – jmelger Sep 29 '22 at 19:34
  • this is a trivial error that could be avoided by carefully reading any online example on basic oop in Lua. please read the Lua manual and make sure you understand what __index does as you obviously don't know it. – Piglet Sep 30 '22 at 06:00

1 Answers1

0

You're calling m["print_message"] which is a nil value. Calling nil values is not allowed as it doesn't make any sense to call a nil value.

If you index a field that does not exist in a table, Lua will check wether the table has a metatable and if that metatable has a field __index.

While that field exists in m it does not exist in its metatable class_b.

class_b.__index must refer to class_b to make this work.

Piglet
  • 27,501
  • 3
  • 20
  • 43