Help with function inside table

When I do this:

local Car = {}

-- Properties
Car.Model = "EpicModel"
Car.Color = "Blue"
Car.Speed = 0

-- States
Car.isDriving = false

-- Behavior
Car.Drive = function()
	Car.isDriving = true
end

Car.Stop = function()
	Car.Speed = 0
	Car.isDriving = false
end

Car.SetSpeed = function(speed)
	if Car.isDriving then
		Car.Speed = speed
	end
end

print(Car.Speed)

Car:Drive()

Car:SetSpeed(50)

print(Car.Speed)

it prints:
0
table: 0x533ec3e34ecc13ec

and when I don’t put the semi-colons at the end of code the and put dots:

local Car = {}

-- Properties
Car.Model = "EpicModel"
Car.Color = "Blue"
Car.Speed = 0

-- States
Car.isDriving = false

-- Behavior
Car.Drive = function()
	Car.isDriving = true
end

Car.Stop = function()
	Car.Speed = 0
	Car.isDriving = false
end

Car.SetSpeed = function(speed)
	if Car.isDriving then
		Car.Speed = speed
	end
end

print(Car.Speed)

Car.Drive()

Car.SetSpeed(50)

print(Car.Speed)

it prints what I want:
0

50

Why is this?

1 Like

a:b(...) is syntax sugar for a.b(a, ...).

So when you did Car:SetSpeed(50) it was passing Car as the first argument, 50 as the second argument. So the second argument got discarded and the speed was set to itself.

recursive tables ftw, try print(Car.Speed.Speed.Speed.Speed.Speed.Speed.Speed.Speed.Speed) and keep going

If you define functions using . then call it with ., don’t be inconsistent.

1 Like