Reputation: 13
I'm trying to get some code working from this video: Lua Tutorial 9: OOP and Metatables about 11 minutes into the video
I'm new to lua but i have programming experience so after going through the basics of the language i'd thought i'd learn some ways to do oop. In my code i've replaced vector3 with Vector2 since i need to work in 2d for now. Lua's powerful tables is something that is something i really need to understand to be more fluent in the language of coarse .
however i get an error: input:38: attempt to perform arithmetic on a table value (local 'v1')
I have the same issue testing in: the lua demo interpreter The code i'm trying out:
Vector2 = {x = 0, y = 0}
Vector2.prototype = {x = 0, y = 0}
Vector2.mt = {}
Vector2.new = function()
local vec = {}
setmetatable(vec, Vector2, mt)
for k, v in pairs(Vector2) do
vec[k] = v
end
return vec
end
Vector2.mt.__add = function(v1, v2)
local vec = Vector2.new()
vec.x = v1.x + v2.x
vec.y = v1.y + v2.y
return vec
end
function draw()
local v1 = Vector2.new()
local v2 = Vector2.new()
v1.x = 10
v1.y = 34
v2.x = 20
v2.y = 22
v1 = v1 + v2
print(v1.x)
end
draw()
Any thoughts. Thanks.
Upvotes: 1
Views: 104
Reputation: 5847
You've made a typo when copied text from the video.
The line setmetatable(vec, Vector2, mt)
should be setmetatable(vec, Vector2.mt)
Upvotes: 1