Search code examples
luagarrys-mod

How to fix 'attempt to call method 'addMoney' (a nil value)' error?


I have two .lua file, one named sv_money.lua and the other economy.lua

The code in sv_money.lua is :

local meta = FindMetaTable("Player")
local PlayersMoney = {}

function meta:addMoney(amount)
    if not amount then return false end

    PlayersMoney[self:SteamID64()] = PlayersMoney[self:SteamID64()] + amount
end

And in economy.lua :

for k, v in pairs(player.GetAll()) do
    v:addMoney(60)
    Notify(v, "You've received 60€.", 5, "Generic" )
end

The expected result is the notification "You've received..." on players screen but the actual result is the error :

Lua Error: [ERROR] addons/economy/lua/autorun/economy.lua:63: attempt to call method 'addMoney' (a nil value)
    1. unknown - addons/economy/lua/autorun/economy.lua:63 

For an unknown reason to me this code in economy.lua works :

hook.Add("PlayerSpawnProp", "Cost", function(ply, class)
        if not ply:canAfford(10) then
            Notify(ply, "You don't have enough money !", 5, "Error" )
            return false
        else
            Notify(ply, "You've spent 10€ to spawn this prop.", 5, "Generic" )
            ply:addMoney(-10)
            return true
        end
end)

Solution

  • The problem was that economy.lua was executed client-side while my code was for server-side.