• Metatables?
    4 replies, posted
What are they? I've never touched on them but they seem like an important aspect of GMod Lua, where do I start?
[url=www.google.com]This is what you are looking for[/url]
[url]http://wiki.garrysmod.com/?title=Understanding_metatables[/url]
Look [url=http://www.facepunch.com/showthread.php?t=631215&highlight=metatable]here[/url]. I think Deco explains it very well.
If you want to learn how to use metatable to make functions for your players, look at this: [lua] local meta = FindMetaTable( "Player" ) -- Grabs player object for us to make functions with if (!meta) then return end --if not a valid metatable then do nothing function meta:SetTotalScore( num ) --This is a made up function. The first argument is a number, but you could call it anything you want. You could call it "lol" if you wanted. self:SetNWInt( "TScore", num ) --Make up an original Networked Integer if you are setting a number. end function meta:GetTotalScore() --This retrieves that Networked Integer return self:GetNWInt( "TScore" ) --This returns the NWInt "TScore", therefore this function is basically equal to whatever you set in SetTotalScore. end function meta:SetMyWords( words ) --Lets make another function. As you can see, the args can be called whatever you want. self:SetNWString( "MadeUpWords", words ) --This one is a string this time, so make up an original Networked String. end function meta:GetMyWords() --This retrieves that Networked String return self:GetNWString( "MadeUpWords" ) --See? end function SetSomeStuffUp(ply) --Here is an example function called somewhere else. ply:SetTotalScore(9001) --Set the player's total score. As you can see, 9001 is the "num" argument shown earlier. ply:SetMyWords("Metatables!") --Set the player's total score. As you can see print(ply:GetTotalScore()) --this should print a number that's OVER 9000!!!! end function LetsDoStuff(ply) --Here is an example function called somewhere else. print("What's your favorite meme?") if ply:GetTotalScore() > 9000 then print("It's over 9000!") else print("IDK, my score is only "..ply:GetTotalScore()) end print("What do you understand?") print(ply:GetMyWords()) end /*Console should print: "What's your favorite meme?" "It's over 9000!" "What do you understand?" "Metatables!"*/ [/lua]
Sorry, you need to Log In to post a reply to this thread.