bigtunacan
bigtunacan

Reputation: 4996

How to split functions of a single class across multiple files in Lua?

What is the proper way to split multiple functions of a single class across files in Lua?

In the following example I would like to split the math and spelling functions across separate files.

CardsScene = Core.class(Sprite) 

function CardsScene:basicMathInit()
end

function CardsScene:basicMathIdle()
end

function CardsScene:basicMathAnswer()
end

function CardsScene:basicSpellingInit()
end

function CardsScene:basicSpellingIdle()
end

function CardsScene:basicSpellingAnswer()
end

Upvotes: 1

Views: 1301

Answers (2)

Tom Blodget
Tom Blodget

Reputation: 20812

Assuming you don't declare CardsScene as a local in any of your files, it's a global.

Any code that runs after you set its value, will use the table created by Core.class(Sprite). In Lua, functions are not declared. They are values created at runtime. When you run a statement like:

function CardsScene:basicMathAnswer()
end 

it creates a function value and assigns it to the basicMathAnswer field in the table referred to by the value that the expression CardsScene currently evaluates to.

So, go ahead and move any or all of those statements with function definitions and assignments to as many files as you want. Just be sure to execute them all, after the one that assigns the global variable CardsScene.

Upvotes: 1

Piglet
Piglet

Reputation: 28994

Make yourself familiar with Lua modules and the standard function require

https://www.lua.org/pil/8.1.html https://www.lua.org/manual/5.3/manual.html#pdf-require

You can execute Lua files like functions.

File A.lua:

print("hello this is from file A")

File B.lua:

require("A")
print("and this is from file B")

once you run B.lua you will get the following output:

hello this is from file A

and this is from file B

Once you understood what's happening you can implement your table members across multiple files.

I would recommend to not split one table across multiple files. I'd rather have a separate table for Math and Spelling and a third table that combines them to a CardsScene. Not just 2 working on the same table.

Upvotes: 1

Related Questions