jmelger
jmelger

Reputation: 87

Importing class and using its methods accross files

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.

Upvotes: 0

Views: 220

Answers (1)

Piglet
Piglet

Reputation: 28994

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.

Upvotes: 0

Related Questions