AndrewShmig
AndrewShmig

Reputation: 4923

What type of data does string.byte return?

What type of data does string.byte return in this sample code:

s = string.byte("hello", 1, 6)

type(s) returns "number", but why then does print output 6 numbers and not 1?

Upvotes: 6

Views: 10685

Answers (2)

Overkill
Overkill

Reputation: 46

The output is the ASCII code of the character - see http://www.asciitable.com/

You can use a for loop to iter if you want -

s = "hello";
for i=1,string.len(s) do print(string.byte(s,i)) end;

To turn them back into text, you can use string.char() --

s = "hello";
for i=1,string.len(s) do print(string.char(string.byte(s,i))) end;

you can look into using an array to work with the output: http://www.lua.org/pil/11.1.html

s = "hello"; a = {};
for i=1,string.len(s) do a[i] = string.byte(s,i) end;
for i=1,table.getn(a) do print(a[i]) end;

Upvotes: 1

Ryan Stein
Ryan Stein

Reputation: 8000

string.byte returns multiple numbers, if you tell it to do so. The reason print is displaying five numbers instead of one is because it is capturing all of the return values, whereas with an assignment, only the first value is used and the rest are discarded.

local h = string.byte'hello' -- 104, returns only the first byte
local e = string.byte('hello', 2) -- 101, specified index of 2
local s = string.byte('hello', 1, 6) -- 104 101 108 108 111,
                                     -- but s is the only variable available,
                                     -- so it receives just 104
local a, b = string.byte('hello', 1, 6) -- same thing, except now there are two
                                        -- variables available, thus:
                                        -- a = 104 & b = 101
print(string.byte('hello', 1, 6))
104     101     108     108     111
print(string.byte('hello', 1, 6), 0) -- in this case, only the first value from
                                     -- the multiple return is used because there
                                     -- is another argument after the results
104     0

I'd suggest reading up on how multiple results and vararg expressions work in Lua.

Lua Manual 3.4.10 - Function Definitions

[...] If a vararg expression is used inside another expression or in the middle of a list of expressions, then its return list is adjusted to one element. If the expression is used as the last element of a list of expressions, then no adjustment is made (unless that last expression is enclosed in parentheses).

Upvotes: 7

Related Questions