lua-users home
lua-l archive

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


On Friday, January 23, 2015 01:44:27 PM Soni L. wrote:

> How can I quickly concatenate 2 tables? (or convert a whole string to a

> table of bytes/numbers)

>

> For example:

>

> local t = {string.byte(str, 1, stack_limit)} .. {string.byte(str,

> stack_limit+1, stack_limit*2)} -- .. etc

 

do

local stringtobytes_mt = {

__index = function(t, k)

local i = math.tointeger(k) -- Lua 5.3

assert(i == k)

local b = t.string:byte(i)

rawset(t, i, b)

return b

end,

__newindex = function(t, k, v)

error("")

end,

__len = function(t)

return #t.string

end

}

 

function stringtobytes(str)

return setmetatable({string=str}, stringtobytes_mt)

end

end

 

local t = stringtobytes "Hello World!"

print(#t) -- 12

print(t[6]) -- 32

for _,b in ipairs(t) do io.write(string.format("%02X", b)) end io.write "\n"

-- 48656C6C6F20576F726C6421

 

And I'm not sure the rawset is even needed as string.byte may be cheap enough. Always profile before optimizing.

 

--

tom <telliamed@whoopdedo.org>