I use this method to load lua file as a script : https://love2d.org/wiki/love.filesystem.load
The script should contain 3 functions create, draw and update but not globaly defined but as local. So at the end of the script i need to put a table and return it.
Looks nice? Not that much. Any idea of how i can call a function defined in a chunk without returning it at the end as a variable which contains the functions prepared? Something like chunk.draw() or chunk.update() or perhaps chunk(params)? to call the update(params) when needed?
local function create()
end
local function draw()
end
local function update()
end
-- i define a table here to export the functions
local shader = {
create = create,
draw = draw,
update = update,
}
-- glsl shader code
shader.glsl = [[
extern number time;
vec4 effect(vec4 color, Image texture, vec2 texture_coords, vec2 pixel_coords)
{
return vec4((1.0+sin(time))/2.0, abs(cos(time)), abs(sin(time)), 1.0);
}
]]
-- glsl shader parameters
shader.params = {
-- time that the shader uses in update
time = 0,
}
return shader
Last edited by Rigachupe on Mon Jul 29, 2024 3:34 pm, edited 1 time in total.
You put those functions into a table, return it into a variable called chunk, and then you call chunk.draw(), chunk.update(), etc.
you said so yourself :/
Me and my stuff True Neutral Aspirant. Why, yes, i do indeed enjoy sarcastically correcting others when they make the most blatant of spelling mistakes. No bullying or trolling the innocent tho.
zorg wrote: ↑Mon Jul 29, 2024 11:36 am
You put those functions into a table, return it into a variable called chunk, and then you call chunk.draw(), chunk.update(), etc.
you said so yourself :/
No no. The compiler return the chunk as a pointer and in debugger i see it as a single function. The table returned would contain the possible way o calling t.draw() etc but i would like to avoid defining tht kind of table in each script if you understand.
AFAIK returning a table, or changing the global environment, are the usual ways this is done.
If you want to try something different, I think you could set with a custom environment table on the chunk function.
local function loadLibraryScript(path)
local chunkEnv = {
love = love,
math = math,
(...)
}
local chunk = love.filesystem.load(path)
setfenv(chunk, chunkEnv)
-- Probably best to use pcall() to handle errors in the line below.
chunk()
-- "Global" names should now be automatically stored in the custom chunkEnv instead of _G.
return chunkEnv
end
local myChunk = loadLibraryScript(.....)
myChunk.draw()
Another traditional way to do it is to define the table to be returned at the top and then define the functions you want to export in that table to begin with. This is a bit shorter and saves you from duplicating the names of everything. Perhaps you like the look of that better.
local M = {} -- By a certain tradition called 'M' for 'Module' (it's short).
function M.create()
end
function M.update(dt)
end
function M.draw()
end
return M