A module script problem

i accidentally make a mistake

--module script
local fuel = 100
local module = {}
function module.run ()
    fuel -= 1
end
return module

so many car will access this run function which will change the fuel this will change the fuel of all the car which I don’t want how to give each car own fuel value instead of a static one like this

1 Like

You could always just give each car an attribute called Fuel and save yourself the hassle lol
Attributes are great!

Either that or:

  • A. Every car has a module in it.
  • B. You keep a table in the module of every car thats spawned in, then create logic that finds that car in the table and decreases its fuel
  • C. Feed the whole dev community, we’re hungry people.
1 Like

but is there any like faster way to do this instead of creating attributes the real code have more than 20 variables and I don’t want to create 20 attributes plus in java there is a way to do this so there must be a way to do it in lua right?

Well, first you need to create a car

local car = {}
car.new = function()
    return {fuel = 100}
end

car.run = function(carTable)
    carTanle.fuel -= 1
end

return car

That’s the general idea. With metatables you can make it a bit more self contained (or at least feel more self contained since it will look up the function in the function table if your data table doesn’t have an entry named that.

local car = {}
car.__index = car

car.new = function()
    local thisCar = setmetatable({}, car)
    thisCar.fuel = 100
    return thisCar
end

car:run = function()
    self.fuel -= 1
end

return car

--in another script to use
local c = require(car)
local myCar = c.new()
myCar:run()

(Might have a typo or ten. Wrote this quickly on mobile)

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.