lua-users home
lua-l archive

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


> 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

There is nothing wrong with this approach, quite the opposite. Just
two details:

- 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.

-- Roberto