lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Rici Lake wrote:
I know, it's always been that way. But is there really a compelling reason?

This has been niggling at the back of my mind for a while. From an implementation viewpoint, there would be no problem using a special type for keys for empty Nodes. I don't believe it would slow things down at all or complicate the code (since there is already a special type for dead keys.)

I'm motivated to ask after having glanced at <http://rgrig.blogspot.com/2005/11/writing-readable-code.html>. My little solution to his challenge (which basically involves inverting a table, although that's not the way it was phrased) looks like this:

function firstindex(vec, first, last)
   first, last = first or 1, last or #vec
   local index, retval = {}, {}
   for i = last, first, -1 do index[vec[i]] = i end
   for i = first, last do retval[i] = index[vec[i]] end
   return retval
end

My solution (I didn't looked at your before doing it, to avoid to be spoiled...):

local x = { 0, 1, 4, 2, 4, 1, 0, 2 }
local x = { 'a', 'b', 'e', 'c', 'e', 'b', 'a', 'c' }
local y, found = {}, {}

for i, val in ipairs(x) do
 if found[val] == nil then
    y[i], found[val] = i - 1, i
  else
    y[i] = found[val] - 1
  end
end
print(table.concat(y, ", "))

Shows the solution as requested (0-based).

BTW, how can you have a nil element in the list? In Lua 5.0, putting it in the init. array will stop the array right there, and setting a value to nil removes it. Is it a Lua 5.1 new capability or did I miss something?

--
Philippe Lhoste
--  (near) Paris -- France
--  http://Phi.Lho.free.fr
--  --  --  --  --  --  --  --  --  --  --  --  --  --