jprbest
jprbest

Reputation: 737

store string of bytes in table in lua

i need to store a string of bytes in a table in lua, how I can do it thanks Jp

Upvotes: 0

Views: 2619

Answers (2)

lhf
lhf

Reputation: 72352

Is that what you mean?

s="some string"
t={s:byte(1,#s)}

Upvotes: 3

Michal Kottman
Michal Kottman

Reputation: 16753

A Lua string is exactly what you wrote - a string of bytes. Lua is different from C-like languages in that it is 8-bit clean, meaning that you can even store embedded zero '\0' inside strings - the length of the string is held separately and is not based on where '\0' is.

You did not write where you want those bytes from (what is the source), so let's assume you are reading from a file. In the following example, f is a file handle obtained by calling io.open(filename), and t is a table (t = {}).

local str = f:read(100) -- will read up to 100 bytes from file handle f
t[#t + 1] = str         -- will append the string to the end of table t
table.insert(t, str)    -- alternative way of achieving the same

Upvotes: 2

Related Questions