I'm currently trying to learn tables so i've attempted to make a table print into console. This is the code i have currently:
[code]
local BadNames = { "Sleepy", "Sleepy2" }
local function IsYourNameBad()
for k, v in pairs( BadNames ) do
print(BadNames)
end
end
concommand.Add("checkbadnames", IsYourNameBad)
[/code]
The output i get in console is:
[code]
table: 0x14f96040
[/code]
I don't see what i am doing wrong.. could somebody please explain to me? Thanks.
-snip-
Just realised how much of an idiot I was, I guess that's what I get for typing this at 5am.
[QUOTE=Promptitude;49462447][url=https://wiki.garrysmod.com/page/Global/PrintTable] PrintTable [/url] is used to print tables instead of just strings as a table is not the same as a string.
[CODE]PrintTable(BadNames)[/CODE]
If you're trying to access the table use something like:
[CODE]for i, v in pairs( BadNames ) do
print( BadNames[i] ) -- i is the number of the for loop has been ran through so it gets what is at the i position in the table.
end[/CODE]
or even:
[CODE]for i = 1, #BadNames do
print( BadNames[i] ) -- i is the number of times the for loop has been ran through so it gets what is at the i position in the table.
end[/CODE][/QUOTE]
Really dude? Why do you use BadNames[i] when you have the value already? (1st example)
[CODE]
local BadNames = { "Sleepy", "Sleepy2" }
local function IsYourNameBad()
for k, v in pairs( BadNames ) do -- for index, value in pairs...
print( v ) -- v is the value
end
end
concommand.Add("checkbadnames", IsYourNameBad)
[/CODE]
The problem in your code is that you are printing the table and not value.
So I'll explain a bit better than the other guys.
Doing print(table) prints the memory address of of table while PrintTable(table) prints each individual key and its corresponding value.
Know what kind of loop to use depends on the situation.
for i = 1, 3, 1 do - The numeric for, it's the fastest type of loop but only works with tables that have numeric keys and no holes. So if table[1] is an entity, table[2] is nil, and table[3] is a string it will error because table[2] is nil. The numeric for is a more traditional loop.
for i, v in ipairs(table) do - This is the same as above but except of having to do table[i] you can just do v. So for example you could do print(v) where in the numeric for you have to do print(table[i]). ipairs is barely slower than the numeric for and also doesn't like holes in tables.
for k, v in pairs(table) do - Works with any type of keys (strings, tables, entities, whatever) and doesn't care about holes in tables. While it is the slowest it still pretty fast.
Sorry, you need to Log In to post a reply to this thread.