Strange Error with "LocalPlayer()

[lua]
LocalPlayer().ClassData = {}
for k,v in pairs(GlobalClassTable) do
! LocalPlayer().ClassData[v] = {}
LocalPlayer().ClassData[v].xp = 0
LocalPlayer().ClassData[v].lvl = 1
print(" cl “…LocalPlayer().ClassData[v].xp…” “…LocalPlayer().ClassData[v].lvl…” . ")
end
[/lua]

The error I am getting:



 newgm\gamemode\classes.lua:105: attempt to index field 'ClassData' (a nil value)


The line with the “!” is line 105

It makes no sense to me. Unless LocalPlayer() is broken or doesn’t work in singleplayer or something odd. It’s doing my head in.

Bad Reading x 1

Line 1.

Yeah, I litterally define it right before the line it sais it’s nil.

[editline]08:51AM[/editline]

post 1,400!!

You don’t happen to be calling LocalPlayer() on the server?

When the errors displays, in which color the text is in the console (orange or blue) ?

This happens because you are probably (can’t tell) running this without a hook try it in initalize or run a think hook until the LocalPlayer has been created and do your initial spawn stuff there, then kill the think hook.

What I mean by the think hook:

[lua]
function ready()
if ValidEntity(LocalPlayer()) && LocalPlayer():Alive() then
RunConsoleCommand(“ready”)
ready_removed = true
//DO INIT SPAWN STUFF HERE

	hook.Remove( "Think", "READY" )
end

end

hook.Add(“Think”, “READY”, ready)
[/lua]

The concommand is optional but a good way to tell the server the client is ready to be sent stuff etc.

Random exclamation mark on line 3?

.

I am calling it on the client, the text is yellow.

It doesn’t run the 1st time, but when I reload the gamemode, it works. However in the other location I’m using i, which is HUDPaint; it works the 1st time somewhat by saying that ClassData is nil, then it sais that field “?” is nil…so…

I have no clue why this isn’t working. I may end up changing how I build the table. I may do one big global table with all the player’s steam ID’s in it and have it like that and simply create a player’s portion of it when they spawn the first time.

Where is this code when it runs and gives the error?

That’s because when you run your code the first time there is no LocalPlayer yet. It’s like conman420 said but you should be using **[Gamemode.InitPostEntity

http://wiki.garrysmod.com/favicon.ico](wiki.garrysmod.com/?title=Gamemode.InitPostEntity)**.

[lua]hook.Add( “InitPostEntity”, “ClassDataSetup”, function()
local ply = LocalPlayer()
ply.ClassData = {}
for k,v in pairs(GlobalClassTable) do
ply.ClassData[v] = {}
ply.ClassData[v].xp = 0
ply.ClassData[v].lvl = 1
print(" cl “…ply.ClassData[v].xp…” “…ply.ClassData[v].lvl…” . ")
end
end)[/lua]
:eng101:

Bad bad reading


(User was banned for this post ("Why reply?" - mahalis))