Hi Friends
It seems there are different ways to write LUA modules.
1- what difference between these types:
The first one:
local function f1()
print("f1");
end
local myModule = {}
myModule.f1 = f1
return myModule
The second one:
local myModule = {}
function myModule.f1()
print("f1")
end
return myModule
and another question:
imagine I have “myModule” with 50 functions on it, i use “require myModule” to include it to my project but i use just one function of that module not all of them, in this case does it includes all 50 functions to my project or just that one i used?
thanks a lot
There is no difference between the two examples you provided. They are semantically equivalent. function a_table.fname() ... end is syntax sugar for a_table.fname = function () ... end.
Yes, all the functions will be included in your module, but there’s absolutely nothing to fear. Creating a Lua function is just a very tiny allocation that only happens once when your module is require()-d, especially if it doesn’t use any upvalues (variables from outside the function). The performance impact is negligible. My advice to you is to only worry about optimising code that runs often (inside a loop or at every frame). For everything else, focus on readability first.
But, I mean, why? I’m pretty sure there isn’t much perf difference between setting that function at table init time and setting it immediately after table creation. Heck, the JIT compiler probably generates the same code for that situation anyway. You’re sacrificing readability for no good reason.
Yeah, it’s probably bad practice, but it’s just how I’m wired. It looks easier to inderstand to me. Performance isn’t why I’m doing it.
I didn’t mean that as a suggestion if how it should be done, rather another example how it can be done, that is, that all of these have the same result.
Thanks guys
what should i do to get autocomplete suggestions for my modules in that file i use myModule? i.e i use that module i have wrote on first post, in my main code i include it this way too:
local myModule = require("main.myModule")
so when i write myModule in my editor and i press “.” i expect to see f1() in suggestions, but i can’t see anything . should i use something more to see list of functions of my module in suggestions?
I have add @param above my funtion too but i can’t see any info while typing:
--- @param arg input_string
function myModule.f1(arg)
print(arg)
end