Post Reply 
Adding an entry to a vector or list
09-25-2023, 11:22 PM
Post: #6
RE: Adding an entry to a vector or list
(09-24-2023 04:13 PM)Tyann Wrote:  You can also use list(-1):=expr, in which case expr will be added to the top of the list.

Is negative index HOME table insertion documented anywhere?

This is very confusing, positive index for table assignment, non-positive index for table insertion.
Table lost its nice boundary checks, with possibly nasty bug, especially if index were computed.

Also, if index 0 is for end-of-list, -1 should really be one before, not head-of-list. It made no sense.

Anyway, this is Lua simulation of how HOME table behave. (based from trial and error)
Note that "=" is in quote, it is not assignment, but insertion! How confusing!

I think table insertion should really be a separate function, like Lua's table.insert

Code:
home_meta = {
    __index = function(a,i)                  -- t[non-existent i]
        if i==0 then return rawget(t,#t) end -- t[0] == t[#t]
        return "Error: " .. (i<0 and "Bad argument type" or "Invalid Input")
    end,
    __newindex = function(t,i,v)             -- t[non-existent i] "=" v
        i = i==0 and (#t+1) or abs(i)        -- t[0] == t[#t+1]
        if i <= #t then return table.insert(t,i,v) end        
        for j = #t+1, i-1 do rawset(t,j,0) end; rawset(t,i,v)        
    end,   
}


lua> home_table = function(t) return setmetatable(t, home_meta) end

lua> t = home_table {1,2,3}
lua> t[1], t[2], t[3], t[0] -- home table lookup behavior, t[0] ≡ t[#t]
1      2      3      3
lua> t[-1], t[4]               -- home table error msg for bad indexes
Error: Bad argument type      Error: Invalid Input

lua> ;require'pprint'        -- home table insertion / extension behavior
lua> pprint(t)
{ 1, 2, 3 }
lua> t[0]=5; pprint(t)
{ 1, 2, 3, 5 }
lua> t[-4]=4; pprint(t)
{ 1, 2, 3, 4, 5 }
lua> t[-10]=10; pprint(t)
{ 1, 2, 3, 4, 5, 0, 0, 0, 0, 10 }

FYI, last operation crashed HP Prime emulator.
Find all posts by this user
Quote this message in a reply
Post Reply 


Messages In This Thread
RE: Adding an entry to a vector or list - Albert Chan - 09-25-2023 11:22 PM



User(s) browsing this thread: 1 Guest(s)