[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Binary and octal literals not currently supported by lua
- From: Roberto Ierusalimschy <roberto@...>
- Date: Wed, 26 Jan 2022 06:38:16 -0300
> As a workaround i've written small lua function to handle this for me, but
> it seems as a quite inneficient and probably very wrong solution. So i
> would strongly prefer the binary notation to be part of lua.
> -- Create number from string containing binary notation (up to 63b)
> -- Any character other than 0 or 1 will get ignored
> -- eg.: b('00101010') will get you 42
> function b(str)
> if type(vals) ~= "string" then
> str = tostring(str)
> local n = 0;
> for c in str:gmatch"." do
> if c=='0' then; n = n << 1; end;
> if c=='1' then; n = (n << 1) | 1; end;
> return n;
There is nothing wrong with this approach, quite the opposite. Just
- You can write b'00101010' instead of b('00101010').
- You can use 'tonumber' to do the conversion.
About performance, as with most constants in programs, it is good
practice to predefine them, so that these conversions are done
only once for each constant.