• meaning of "for k,v"?
    8 replies, posted
i'm sorry this is probably the worst question to ask, but i've been cross-referencing different code segments in many gamemodes, and i come across the statement "for k,v" or "for k,v in pairs". could someone explain what this means, and give a short example please?, thank you very much :)
k,v is shorthand for Key,Value, used in tables. Value is the thing you're enterring and Key is the "ID" it's given.
Basically, it loops through every entry in the table, where k is the index and v is the value.
[lua] tbl = { 1, "testing" } tbl.test = "table" for k,v in pairs(tbl) do print("in our \"" .. k .. "\" key there is: \"" .. v .. "\" as the value") end [/lua] This out puts: [code] in our "1" key there is: "1" as the value in our "2" key there is: "testing" as the value in our "test" key there is: "table" as the value [/code]
They can be replaced by any other two letters, such as c,d or h,f.
thank you very much, could you give me a situation where this would be useful maybe?
[QUOTE=Yobdren;17167975]They can be replaced by any other two letters, such as c,d or h,f.[/QUOTE] This, however k and v seem more logical since they are rarely used anywhere else, small and easy to remember. Though some tend to use _ instead of k as a dummy if you don't use it. [editline]01:49AM[/editline] [QUOTE=Ghilliedman;17168036]thank you very much, could you give me a situation where this would be useful maybe?[/QUOTE] [lua] for k, v in pairs(player.GetAll()) do v:Kill() --Kill all players on a server. print( "Killed " .. v:Name() ) -- Print to the console who we killed end [/lua]
Thanks guys! you've helped me a lot! 20 kudos to everyone who posted!
[QUOTE=JSharpe;17168037]This, however k and v seem more logical since they are rarely used anywhere else, small and easy to remember. Though some tend to use _ instead of k as a dummy if you don't use it.[/QUOTE] It's a critical piece of information if you intend to have for loops in for loops.
Sorry, you need to Log In to post a reply to this thread.