How to load a lua file as a function (OLD: Adding variables to a table return nil)
Posted: Thu Aug 10, 2023 5:48 pm
For some reason, a value doesn't get added into a table, and when I try to output or call it, it just returns nil or an error.
I tried using the unpack() function, load() but neither of them didn't work.
Also I'm using a loader I wrote so it could be easier to create objects.
Right now the object has only one event called step(), and when I try to add it into an object from the files it doesn't get added.
Something like this:
And then from the files the table should have the methods the "events" folder has
But for some reason the function doesn't get added.
Sorry for bad English.
I tried using the unpack() function, load() but neither of them didn't work.
Code: Select all
function create_object(name, options, events)
local obj = {
type = name,
x = 0,
y = 0,
width = 0,
height = 0,
-- ...
}
for key, value in pairs(options) do
if obj[key] then
obj[key] = value
end
end
for key, value in pairs(events) do
-- for some reason it doesn't add new variables into a table
obj[key] = value
end
_G[name] = obj
end
Code: Select all
function(folder)
if not love.filesystem.getInfo("objects/" .. folder .. "/obj_info.lua") then
return
end
local obj_info = dofile("objects/" .. folder .. "/obj_info.lua")
local files = lf.getDirectoryItems("objects/" .. folder .. "/events")
local events = {}
for i=1, #files do
local file = files[i]
-- https://stackoverflow.com/questions/18884396/extracting-filename-only-with-pattern-matching
-- "step.lua" > "step"
local filename = file:match("(.+)%..+")
local filehandler = io.open("objects/" .. folder .. "/events/" .. file)
local data = filehandler:read("*all")
filehandler:close()
-- print(data)
events[filename] = (function(self)
print("works")
load(data)()
end)
end
create_object(obj_info.name, obj_info.properties, events)
end
Something like this:
Code: Select all
object
events
step.lua
obj_info.lua
Code: Select all
{
-- some variables and methods
-- ...
step = function(self)
load(data)()
end
}
Sorry for bad English.