lua-users home
lua-l archive

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


I have also written the manual index logic on occasion since it avoids the
getn/setn logic in table.insert. On the other hand, one then potentially
needs to do a setn at the end and the code in general becomes more
convoluted.

One optimization I have been making more and more is to lift the table
lookup for table.insert out of the loop -- i.e.:

    local buff = {}
    local tinsert = table.insert
    for j = 1,n do
        tinsert( buffer, "hello\n" )
    end
    local s = table.concat( buff )

That being said, would it be fruitful to try to standardize on a way to
write accumulators for Lua as the counterpart to iterators? By fruitful this
could mean either in terms of performance or in terms of ease of expression
of common idioms without hurting efficiency. There was a TOPLAS paper years
ago on adding iterators and accumulators to Modula-2+ that I remember looked
rather nice in what it achieved. I don't have it handy to me right now,
however, to refresh my memory.

Mark
    
on 9/26/04 12:50 PM, Mike Pall at mikelu-0409@mike.de wrote:

> Umm, please have a look at the original version:
> 
> local buff = {}
> for i=1,n do
> table.insert(buff, "hello\n")
> end
> local s = table.concat(buff)
> 
> This *does* construct a list of strings and then joins it. And this version
> was accepted ... I have just replaced the function call with equivalent
> inlined code. And I should mention that table.concat() does the real work
> of growing a string buffer piecewise (as demanded by the rules).
> 
> Well, I guess you'd have to discuss this with them ... but another general
> rule is to use whatever idiom is common in a language.
> 
> And I certainly have used this style in my code, e.g.:
> 
> local rsp = {}
> local i = 2
> rsp[1] = "HTTP/1.1 200 OK"
> for k, v in pairs(self.rspheaders) do rsp[i] = v; i = i +1 end
> rsp[i] = ""
> local rspstr = table.concat(rsp, "\013\010", 1, i+1)