lua-users home
lua-l archive

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


Hello,
lua recently received native bitwise operators:
http://lua-users.org/wiki/BitwiseOperators

But there is no way to enter binary literals. I would find such feature to be quite helpful addition to these new bitwise operations. While i understand that one can easily precalculate the literals before entering into the code, sometimes it can be useful when programming language does this to me, so that bit-fiddling code is easier to read, modify and debug.
Can you please consider adding such feature? eg.:

42 -- decimal works
42

0x2A -- hexadecimal works
42

0b00101010 -- binary fails
stdin:1: malformed number near '0b00101010'

0o52 -- octal fails
stdin:1: malformed number near '0o'

Octal would be nice, but not strictly neccessary. I mostly use it when working with file permission modes and i can live without it just fine. But handling binary on the other hand is daily task for me.

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)
	end
	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;
	end
	return n;
end


Thanks for considering this.

--
S pozdravem
Best regards
     Tomáš Mudruňka - SPOJE.NET s.r.o.