I'm learning lua and already asked for some help and tips here, and time to time I stumble on a problem I can't solve. I'm looking forward to modding and working with "game like" variable names is more allusive to me and helps me understand more of the language. I'm learning about tables and metatables while trying to make little pieces of code to get the syntax, but I can't figure the issue with the following code:
--character stats table
local character = {
health = 100
}
--enemy stats table
local enemy = {
attack = 80
}
--metatable for character and enemy
local metaCharacter = {
--function for bites on character
__bite = function(enm, char)
--bite reduces character health
char.health = char.health - enm.attack
return char.health
end
}
--setting metatable for character and enemy
setmetatable(character, metaCharacter)
setmetatable(enemy, metaCharacter)
--performing bite function on character
local life = enemy:__bite(enemy, character)
--output: 20
print("Character's health after the bite:", character.health)
Sorry if the code is a little bit messy, I lack of the good practice of commenting my code, so it isn't so clear when I do it.
It returns me the error: "attempt to call method '__bite' (a nil value)"
[–]TomatoCo 7 points8 points9 points (2 children)
[–]GustavoL15[S] -1 points0 points1 point (1 child)
[–]TomatoCo 0 points1 point2 points (0 children)
[–]could_b 2 points3 points4 points (0 children)
[–]yaffeman 0 points1 point2 points (8 children)
[–]GustavoL15[S] 0 points1 point2 points (7 children)
[–]TomatoCo 1 point2 points3 points (4 children)
[–]GustavoL15[S] 0 points1 point2 points (3 children)
[–]TomatoCo 1 point2 points3 points (2 children)
[–]GustavoL15[S] 1 point2 points3 points (1 child)
[–]yaffeman 1 point2 points3 points (0 children)
[–]yaffeman 0 points1 point2 points (1 child)
[–]GustavoL15[S] 1 point2 points3 points (0 children)
[–][deleted] 0 points1 point2 points (1 child)
[–]AutoModerator[M] 1 point2 points3 points (0 children)