Lua unpack bug? - lua

I Have stumbled on a weird behavior in Lua unpack function
table1 = {true, nil, true, false, nil, true, nil}
table2 = {true, false, nil, false, nil, true, nil}
a1,b1,c1,d1,e1,f1,g1 = unpack( table1 )
print ("table1:",a1,b1,c1,d1,e1,f1,g1)
a2,b2,c2,d2,e2,f2,g2 = unpack( table2 )
print ("table2:",a2,b2,c2,d2,e2,f2,g2)
Output:
table1: true nil true false nil nil nil
table2: true false nil nil nil nil nil
The second unpack delivers parameters up to the first nil value. I could live with that.
The first table delivers 4? parameters with one being nil in the middle. It has 4 parameters that are not nil, but they aren't the one that are shown.
Could anyone explain this?
This was tried with codepad.org and lua 5.1

The problem can be resolved simply by specifying the beginning and ending indexes to unpack() and using the table.maxn() as the ending index:
table1 = {true, nil, true, false, nil, true, nil}
a1,b1,c1,d1,e1,f1,g1 = unpack( table1, 1, table.maxn(table1) )
print ("table1:",a1,b1,c1,d1,e1,f1,g1)
-->table1: true nil true false nil true nil
The true reason for the discrepancy on how the two tables are handled is in the logic of determining the length of the array portion of the table.
The luaB_unpack() function uses luaL_getn() which is defined in terms of lua_objlen() which calls luaH_getn() for tables. The luaH_getn() looks at the last position of the array, and if it is nil performs a binary search for a boundary in the table ("such that t[i] is non-nil and t[i+1] is nil"). The binary search for the end of the array is the reason that table1 is handled differently then table2.
This should only be an issue if the last entry in the array is nil.
From Programming in Lua (pg.16) (You should buy this book.):
When an array has holes--nil elements inside it--the length operator may assume any of these nil elements as the end marker. Therefore, you should avoid using the length operator on arrays that may contain holes.
The unpack() is using the length operator lua_objlen(), which "may assume any of [the] nil elements as the end" of the array.

2.2 - Values and Types
[...]
The type table implements associative
arrays, that is, arrays that can be
indexed not only with numbers, but
with any value (except nil). Tables
can be heterogeneous; that is, they
can contain values of all types
(except nil). [...]
Given nil to an entry will break the table enumeration and your variables wont be init properly.
Here is a simple example that demonstrates a problematic behavior:
table1 = {true, false, nil, false, nil, true, nil}
for k,v in ipairs(table1) do
print(k, v)
end
output:
1 true
2 false
>Exit code: 0

Related

Lua not not the same as not not

I was using some coroutines and was trying to resume one using not:
if not co == nil then `resume end
and the coroutine wouldn't resume. Though co was nil. It was baffling.
So I eventually tried
if co then `resume end
and it worked!
why isn't not (nil == nil), which is logically false when co is nil and true when it is not which is not the same as as nil which is logically false when co is nil and true otherwise?
I use not all the time to negate the logical expression but now I'm worried that maybe some of my code is buggy. Maybe this only has a problem with coroutines? (and I'm 100% sure that the value is nil, because that is what is printed out, unless nil no longer equals nil)
not co == nil is equivalent to (not co) == nil because of operator precedence.
If co is nil, then not co is true and so different from nil.
In fact, the result of not is always true or false, and so never equal to nil.
Write not (co == nil) or co ~= nil.

How do I create a function that returns the first non-nil, non-empty string passed to it?

I'm trying to implement a function that returns the first non-blank string from the variables passed to it. Unfortunately, some of these variables might be nil, so the naive approach
function first_non_empty(...)
for i, item in ipairs({...}) do
if item ~= nil and item ~= '' then
return item
end
end
return ''
end
doesn't work: ipairs quits out as soon as it encounters a nil value. This can be fixed by changing the requirements so that the variables can't be nil, or by passing the length to the function so table length doesn't have to rely on ipairs, or by wrapping all parameters in a function so that none of them are explicitly nil
function first_non_empty_func(...)
for i, func in ipairs({...}) do
local item = func()
if item ~= nil and item ~= '' then
return item
end
end
return ''
end
function fn(p)
local f = function() return p end
return f
end
-- change callers to first_non_empty_func(fn(a), fn(b), fn(c))
However, both of these solutions complicate the function prototype. Does there exist a function taking an ordered list of parameters, some of which may be nil, which returns the first of those parameters which is both non-nil and not an empty string?
Use table.pack, which preserves all nil entries and returns the number of entries in the n field:
function first_non_empty_pack(...)
local t = table.pack(...)
for i = 1, t.n do
local item = t[i]
if item ~= nil and item ~= '' then
return item
end
end
return ''
end
select('#', ...) can be used to get the number of provided arguments, so here is an alternative that doesn't use table.pack:
function first_non_empty_pack(...)
for i = 1, select('#', ...) do
local item = select(i, ...)
if item ~= nil and item ~= '' then
return item
end
end
return ''
end
Simpler approach is to use recursion. No extra tables created, etc:
function first_non_empty(item, ...)
if item ~= nil and item ~= '' then return item end
return first_non_empty(...)
end
But the list has to end with some ending marker. For example, boolean 'false', indicating there's no non-nil, nonempty strings.

Lua - Table.hasValue returning nil

I have a table something like this:
table = {milk, butter, cheese} -- without "Quotation marks"
I was searching for a way to check if a given value is in the table or not, and found this:
if table.hasValue(table, milk) == true then ...
but it returns nil, any reason why? (it says .hasValue is invalid) or can I get an alternative to check if value exists in that table? I tried several ways like:
if table.milk == true then ...
if table[milk] == true then ...
All of these returns nil or false.
you can try this
items = {milk=true, butter=true, cheese=true}
if items.milk then
...
end
OR
if items.butter == true then
...
end
A Lua table can act as an array or as an associative array (map).
There is no hasValue, but by using a table as an associative array you can easily implement it efficiently:
local table = {
milk = true,
butter = true,
cheese = true,
}
-- has milk?
if table.milk then
print("Has milk!")
end
if table.rocks then
print("Has rocks!")
end
You have a few options here.
One, is to create a set:
local set = {
foo = true,
bar = true,
baz = true
}
Then you check if either of these are in the table:
if set.bar then
The drawback to this approach is that you won't iterate over it in any specific order (pairs returns items in an arbitrary order).
Another option would be to use a function to check each value in a table. This'll be very slow in large tables, which brings us to back to a modification of the first option: A reverse lookup generator: (This is what I'd recommend doing -- unless your set is static)
local data = {"milk", "butter", "cheese"}
local function reverse(tbl, target)
local target = target or {}
for k, v in pairs(tbl) do
target[v] = k
end
return target
end
local revdata = reverse(data)
print(revdata.cheese, revdata.butter, revdata.milk)
-- Output: 3 2 1
This'll generate a set (with the added bonus of giving you the index where the value was in your original table). You can also put the reverse into the same table as the data was in, but this won't go well with numbers (and it'll be messy if you need to generate the reverse again).
If you write table = {milk=true, butter=true, cheese=true}, then you can use if table.milk == true then ....

lua - checking for duplicate data in a string

I have the following string data that I receive as input:
"route1,1234,1,no~,,route2,1234,1,no~,"
It represents two "records" of data... where each record has 4 fields.
I've built code to parse this string into it's individual columns / fields.
But the part that isn't working is when I test to see if I have any duplicates in field 2. Field 2 is the one that currently has "1234" as the value.
Here's the code:
function string:split(delimiter)
local result = { }
local from = 1
local delim_from, delim_to = string.find( self, delimiter, from )
while delim_from do
table.insert( result, string.sub( self, from , delim_from-1 ) )
from = delim_to + 1
delim_from, delim_to = string.find( self, delimiter, from )
end
table.insert( result, string.sub( self, from ) )
return result
end
local check_for_duplicate_entries = function(route_data)
local route
local route_detail = {}
local result =true
local errtxt
local duplicate = false
print("received :" ..route_data)
route = string.gsub(route_data, "~,,", "~")
route = route:sub(1,string.len(route)-2)
print("route :" ..route)
-- break up in to an array
route = string.split(route,"~")
for key, value in pairs(route) do
route_detail[key] = string.split(value,",")
end
local list_of_second_column_only = {}
for key,value in pairs(route_detail) do
local temp = value[2]
print(temp .. " - is the value I'm checking for")
if list_of_second_column_only[temp] == nil then
print("i dont think it exists")
list_of_second_column_only[key] = value[2]
print(list_of_second_column_only[key])
else
--found a duplicate.
return true
end
end
return false
end
print(check_for_duplicate_entries("route1,1234,1,no~,,route2,1234,1,no~,"))
I think where I'm going wrong is the test:
if list_of_second_column_only[temp] == nil then
I think I'm checking for key with the value temp instead of a value with the value that temp contains. But I don't know how to fix the syntax.
Also, I'm wondering if there's a more efficient way to do this.
The number of "records" i receive as input is dynamic / unknown, as is the value of the second column in each record.
Thanks.
EDIT 1
The post I was trying to use as a reference is: Search for an item in a Lua list
In the answer, they show how to test for a record in the table by value, instead of looping through the entire table...
if items["orange"] then
-- do something
end
I was playing around to try and do something similar...
This should be a bit more efficient with only one table creation and less regex matching.
The match does require that you're only interested in dups in the second field.
local function check_for_duplicate_entries(route_data)
assert(type(route_data)=="string")
local field_set = {}
for route in route_data:gmatch"([^~]*)~,?,?" do
local field = route:match",([^,]*)"
if field_set[field] then
return true
else
field_set[field] = true
end
end
return false
end
Try this. It's doing the check on the value of the second field.
I haven't looked at the efficiency.
if list_of_second_column_only[value[2]] == nil then
print("i dont think it exists")
list_of_second_column_only[value[2]] = true
print(list_of_second_column_only[value[2]])
else
--found a duplicate.
return true
end

Can't use where on a column with nil value

I have an Article model
Article.last.publish
=> nil
Article.last.publish != true
=> true
Article.where("publish != ?", true)
=> []
Why am I getting an empty array there?
There are only 2 falsy values in ruby : false and nil
So, if you check the value of !nil then the output will be true
So with your first statement
Article.last.publish # its output is nil
Then your second statement
Article.last.publish != true # this is correct , since !nil = true
But the last one
Article.where("publish != ?", true)
gets converted into a query as
SELECT `articles`.* FROM `articles` WHERE (publish != 1)
which means all articles whose publish value is not true, which means false
and false is not equal to nil.
nil and false are two different falsy values.
Try Article.where(publish: false)

Resources