[lua]: Key with value 1 doesnt do the same as regular 1 - lua

Ive been coding for a mod Im making for a game but I ran into an issue with tables not returning values when the key is entered:
for k, v in pairs(self.math) do
print(self.exce[1])
print(self.exce[k])
print(k)
if self.exce[k] ~= nil then
self.math[k] = nil
end
end
This is the specific part of the script that is breaking. When I run these in the game it returns:
[lua]: true
[lua]: nil
[lua]: 1
Which means is basically saying that 1 is not equal to 1.
The function I used to store my data is
function filterExceptions.server_onException( self, id )
if self.exce[id] == nil then
self.exce[id] = true
self.network:sendToClients( "client_onList", id )
else
self.exce[id] = true
self.network:sendToClients( "client_offList", id )
end
end
In this code the self is a table made by the game you can acces and get game data from or store it in and the id comes from a function I made to get the players id. This id in this case is a 1 (I printed it multiple times).I know that every part of this code is working except for the code in the first block, and escpecialy the part where it tries to do self.exce[k]. Ive tried a lot like going trough every variable in self.exce to see if it was in there and then do stuff, but it still wouldn't work. Its very annoying how lua thinks that k ~= 1 while it definitely is, ive even used similar code in a part that is working.
So what is wrong about this code that its not printing the self.exce[k] while self.exce[1] does work? Dont worry about the creation of the table and stuff, cuz that is already happening whenever it is needed, else it would have given errors about that too.

Putting together a couple different comments and your code here, it looks like the index value of the array in some particular iteration of the "for in pairs" loop (or perhaps all of them, but I'll touch on that in a minute) is a string instead of an integer.
To summarize if you don't want to read the entire thing, "for k, v in pairs" loops will iterate through an entire array, setting k to the index of the value v. It appears your "for in pairs" loop is attempting to iterate through a value of nil where k is a string instead of an integer. You may also want to look into using ipairs instead of pairs in your for loop.
The value of someArray[1]is different than the value of someArray["1"].
The index [1] is a completely different index than the index ["1"] for any given array.
A simple fix would be to use
ind = tonumber(k)
print(self.exce[ind])
This converts the string k to a number type. Be aware this may throw an error if k is a non-numerical string. If the array has any values where the index is a non-numerical string, you may get an error. As the other answer suggests, converting the index k to a string instead of an integer would work as well, and would not throw errors if you used a non-numerical value for your indices.
My guess as to why this is happening would be that the function that you're using to store your data to an array, filterExceptions.server_onException( self, id ), is being passed a string instead of an integer, which would result in the k value being set to a string in that particular iteration of the "for in pairs" loop.
To help better understand this, here's a bit of example code:
a = {true, false, false}
a[1] = true
a["1"] = true
print("Raw for in pairs loop")
for k, v in pairs (a) do
print(type(k)..k)
end
print("For in pairs converting k to a number")
for k, v in pairs (a) do
ind = tonumber(k)
print(type(ind)..ind)
end
print("For in ipairs")
--which I'm not sure I completely understand but
--it seems to skip over any iteration where k is not a number
for k, v in ipairs(a) do
print(type(k)..k)
end
This code produces the following output:
Raw for in pairs loop
number1
number2
number3
string1
For in pairs converting k to a number
number1
number2
number3
number1
For in ipairs
number1
number2
number3
EDIT: Not sure what's going on in the self.math table so I can't comment on that.
EDIT2: I'd also refer you to the following link: lua: iterate through all pairs in table
The top answer there should help understand the difference between pairs and ipairs, if you don't already. You may want to use ipairs to prevent values of k where v == nil from being iterated through with pairs. pairs will iterate through every key/value pair, whereas ipairs will iterate through integer keys starting at 1 and going until it hits a nil value.
EDIT3: I'm sorry this is such a long answer...I just wanted to be thorough.

It apears converting the id to a string fixes this, tough im still confused as to why this same code worked on another block and not this one.
function filterExceptions.server_onException( self, id )
local id2 = tostring(id)
if self.exce[id2] == nil then
self.exce[id2] = true
self.network:sendToClients( "client_onList", id )
else
self.exce[id2] = true
self.network:sendToClients( "client_offList", id )
end
end

Related

LUA: trying to remove a value from a table when it is found in another table

I'm trying to delete a key and value from a table when it is found in another table. I've been using this so far but although it recognizes the duplicate, it always removes the last item in the table...
function get_key_for_value( t, value )
for k,v in pairs(t) do
if v==value then return k
end
return nil
end
end
for k,v in pairs (Iranian_Protected_Groups) do
v[6] = 0
if Springfield_3_Target_Name == v[2] then
v[6] = v[6] + 1
if v[6] > 0 then
local Key_To_Remove = get_key_for_value (Iranian_Protected_Groups, v)
MESSAGE:New( "Shared target is "..v[2], 40):ToBlue()
table.remove (Iranian_Protected_Groups, Key_To_Remove)
end
end
end
any help would be appreciated!
First, you should format your code using standard indentation to make it easier to parse as a human reading the code:
function get_key_for_value(t, value)
for k, v in pairs(t) do
if v == value then
return k
end
return nil
end
end
Look carefully at the for loop. You will never get past the first iteration, because every iteration returns.
Your function is fixed if you move your return nil statement outside the loop. (Though for most purposes, is redundant, because generally no value is equivalent to returning nil).
Before, Key_To_Remove was nil. When passing nil as the index to remove in table.remove, Lua removes the last element. This is convenient when treating a list like a stack, but hid a bug for you in this case.

Why is this function to add the contents of a table together in Lua returning nothing

I am stuck trying to make the contese of a table (all integers) add together to form one sum. I am working on a project where the end goal is a percentage. I am putting the various quantities and storing them in one table. I want to then add all of those integers in the table together to get a sum. I haven't been able to find anything in the standard Library, so I have been tyring to use this:
function sum(t)
local sum = 0
for k,v in pairs(t) do
sum = sum + v
end
return sum
However, its not giving me anything after return sum.... Any and all help would be greatly appreciated.
A more generic solution to this problem of reducing the contents of a table (in this case by summing the elements) is outlined in this answer (warning: no type checking in code sketch).
If your function is not returning at all, it is probably because you are missing an end statement in the function definition.
If your function is returning zero, it is possible that there is a problem with the table you are passing as an argument. In other words, the parameter t may be nil or an empty table. In that case, the function would return zero, the value to which your local sum is initialized.
If you add print (k,v) in the loop for debugging, you can determine whether the function has anything to add. So I would try:
local function sum ( t ) do
print( "t", t ) -- for debugging: should not be nil
local s = 0
for k,v in pairs( t ) do
print(k,v) --for debugging
s = s + v
end
return s
end
local myTestData = { 1, 2, 4, 9 }
print( sum( myTestData) )
The expected output when running this code is
t table: [some index]
1 1
2 2
3 4
4 9
16
Notice that I've changed the variable name inside the function from sum to s. It's preferable not to use the function name sum as the variable holding the sum in the function definition. The local sum in the function overrides the global one, so for example, you couldn't call sum() recursively (i.e. call sum() in the definition of sum()).

Lua table initialization - what is incorrect here [duplicate]

This question already has an answer here:
lua: iterate through all pairs in table
(1 answer)
Closed 8 years ago.
I am trying to initialize and print a table. It just isnt working. Any idea what is wrong with this code?
--!/usr/bin/env lua
local retv = {}
retv["test"] = 1000
for k,v in ipairs(retv) do
print (k,v)
end
It prints nothing. I am sure I am missing something very basic but I cant figure this out.
There are two forms of the for-loop in Lua:
The numeric and the generic for-loop.
ipairs(t) is an iterator constructor returning up to three arguments suitable for the generic for, allowing you to iterate over the initial sequence (indices 1,2,3,...) in order.
Possible implementations:
function ipairs(t)
local i = 0
return function()
i = i + 1
if t[i] ~= nil then
return i, t[i]
end
end
end
local function ipairs_helper(t, i)
i = i + 1
if t[i] ~= nil then
return i, t[i]
end
end
function ipairs(t)
return ipairs_helper, t, 0
end
As you can see, that will never return your entry with key "test".
What you want instead, is pairs(t), which is equivalent to next, t.
That will iterate all elements.
You need to use pairs instead of ipairs. pairs iterates over all keys, ipairs only iterates over keys that form a sequence of integers starting from 1 without gaps. (Whether these keys are stored in the array or the hash part of the table is an implementation detail and may change during the lifetime of the table.)
For example, ipairs({'a', 'b', nil, 'c'}) iterates over keys 1 and 2, stopping at (and not including) 3, as that key is missing from the table.

Reading lua table with word index gives random order

Following is a lua code to read a table with word indexes.
reading this into another table and printing it in output gives random order everytime it is run.
earthquakes = {
date8 = "1992/01/17",
date7 = "1971/02/09",
date6 = "2010/04/04",
date5 = "1987/10/19"
}
sf = string.format
earthquake_num ={}
for k, v in pairs(earthquakes) do
table.insert(earthquake_num, {key=k,value=v})
end
for i, v in pairs (earthquake_num) do
print(sf(" row %d key = %s", i, v.value))
end
OUTPUT :
everytime in different order
This is special feature of Lua 5.2.1 :-)
But what for this feature was introduced?
Anyway, you should not rely on ordering generated by pairs function.
EDIT :
This feature was introduced to fight hash collision attacks on web servers that are using Lua.
Randomized hash algorithm prevents easy generating of strings with equal hashes.
Ordering of table keys generated by pairs function depends on hashes of strings for string-type keys, so string keys are happened to be mixed up on every program run.
From Lua PiL on iterators:
The pairs function, which iterates over all elements in a table, is
similar, except that the iterator function is the next function, which
is a primitive function in Lua:
function pairs (t)
return next, t, nil
end
The call next(t, k), where k is a key of the table t, returns a next key
in the table, in an arbitrary order. (It returns also the
value associated with that key, as a second return value.) The call
next(t, nil) returns a first pair. When there are no more pairs, next
returns nil.
And the enumeration for next states:
next (table [, index])
The order in which the indices are enumerated is not specified,
even for numeric indices. (To traverse a table in numeric order, use a numerical for or the ipairs function.)
As Egor says the pairs iterator returns table values in an arbitrary order. To sort data and return it in a sequenced format you need to use ipairs for example
earthquakes = {
date8 = "1992/01/17",
date7 = "1971/02/09",
date6 = "2010/04/04",
date5 = "1987/10/19"
}
sf = string.format
earthquake_num ={}
for k, v in pairs(earthquakes) do
table.insert(earthquake_num, {key=k,value=v})
end
table.sort(earthquake_num,function(a, b) return a.value < b.value end)
for i, v in ipairs (earthquake_num) do
print(sf(" row %d key = %s", i, v.value))
end
see lua: iterate through all pairs in table for more information.

wrong lua table size when using string key index

Usually for getting table size, the standard table library function # operator works.
However when I make a table which has a string key index, it doesn't work.
local function addWriterIdListToTable()
local returnTable = {}
local requestString = "1234:16 5678:8 9012:1"
local idList = requestString:split(" ")
for i,v in ipairs(idList) do
local oneId = v:split(":")
returnTable[oneId[1]] = oneId[2]
end
for k,v in pairs(returnTable) do
print (k .. " " .. v)
end
print("size of table: " .. #returnTable)
return returnTable
end
I want to trsnform a string to table.
The function "split" parse a string, split it with parameter as a delimiter, and return as table.
The result of a excution above function like below.
1234 16
9012 1
5678 8
size of table: 0
It shows the content of table exactly as I expected, but its count is not.
Anybody to help me?
Thanks in advance.
The # operator tells you the highest numeric index in the table. If there are any gaps in the numeric indexing, it may return the highest below the gap. Basically, the # operator only works right if you're treating your table like a dense array.
If you actually want to know how many entries are in a table, you'll need to iterate over it using the pairs() function and count how many items you get.
function countTableSize(table)
local n = 0
for k, v in pairs(table) do
n = n + 1
end
return n
end
Although I do wonder why you even need to know how many entries are in the table. Typically all you care about is if the table is empty or not, and you can check that by just seeing if next(table) == nil.

Resources