lua-users home
lua-l archive

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


Sorry,
I forgot the callback function...


func = function( pos, tp ) --> this function return the table element value and key, according to the type (tp), array or non-array ('a' or 'n')
    if tp == 'a' then
        return pos * 2
    end

    return 'element' .. tostring( pos ), pos * 3
end


If think the callback function could return only the value of the element, the key should be optional. In this case 'createtable' use the value of the 'for' variable, as we can see at the 'createtable' function proposed. Anyway to 'createtable' function work properly for no-array elements, the callback function may return both value and key.

With this function we can create a table with many structure formats and with a simple call, like this:


t = createtable( 5, 3, func )


its the same of


t = { [1] = 2, [2] = 4, [3] = 6, [4] = 8, [5] = 10, ['element1'] = 3, ['element2'] = 6, ['element3'] = 9 }


[]'s,
mabreu


On Wed, Apr 29, 2009 at 12:30 PM, Marco Antonio Abreu <mabreu.ti@gmail.com> wrote:
Hi Guys,

I want to reopen the topic about table constructor created by Jason Santos:

"Is there a reason why there is no function in the table library to mirror lua_createtable() from the C API?

Would it be a good idea to add such a function?

If there are performance tuning opportunities to be explored by reducing the amount of table.inserts (Yes, I've read Roberto's article on Lua Gems), I would like to be able to make them dynamically and in pure lua".

I suppose it will be very useful if we could create a table with all occurrencies we need direct from Lua. Like Luiz Henrique said "a C binding for lua_createtable" should be nice, but I thought in something beyond. I suppose it could be interesting if we could give the default value to the occurrences created  by the function and, in case of a function, it could be called to return the valeu and its key. What do you think about this?


function createtable( a, n, f, c )

    collectgarbage( 'stop' )
    -- this line below should be the memory allocation with all necessary space for the occurencies - lua_createtable( L, a, n )
    local result = loadstring( 'return {' .. string.rep( 'false,', n + a ) .. '}' )()
   
    if c or type( f ) ~= 'function' then
        for i = 1, a do
            result[ i ] = f
        end
       
        for i = 1, n do
            result[ tostring( i ) ] = f
        end
    else
        local k, v

        for i = 1, a do
            v, k = f( i, 'a' )
            result[ k or i ] = v
        end

        for i = 1, n do
            v, k = f( i, 'n' )
            result[ tostring( k or i ) ] = v
        end
    end

    collectgarbage( 'restart' )
    return result
end




--
Marco Antonio Abreu
Analista de Sistemas



--
Marco Antonio Abreu
Analista de Sistemas