Search code examples
luagarrys-mod

Error: attempt to index local 'self' (a nil value)


I am following a tutorial on Lua, specifically for making a gamemode in the game Garry's Mod. I've been looking at this for a while and I simply can't find what's wrong.

function ply:databaseFolders()
   return "server/example/players/" .. self:ShortSteamID() .. "/"    --ref. A
end


function ply:databasePath()
   return self:databaseFolders() .. "database.txt"    --ERROR line here, goes up
end


function ply:databaseExists()
   local f = file.Exists(self.databasePath(), "DATA")    --goes up here
   return f
end


function ply:databaseCheck()
   self.database = {}
   local f = self:databaseExists()     --goes up here
   ...
end


function GM:PlayerAuthed(ply, steamID, uniqueID)
   ply:databaseCheck()                                         --goes up here
   print("Player: " .. ply:Nick() .. " has gotten authed.")
end

Summary of code: I want to create a database.txt file at the directory above.

Edit1: When all players leave the game, ref. A is reached, but no file created in directory.


Solution

  • When you are calling the function databasePath, you are not using the OOP syntax; and therefore self is not implicitly passed to the function. Henceforth, the error. Change the following:

    function ply:databaseExists()
       local f = file.Exists(self:databasePath(), "DATA")
       -- notice the use of ---> : <--- here
       return f
    end