Quick Links: Download Gideros Studio | Gideros Documentation | Gideros Development Center | Gideros community chat
Lua: bitwise operators with new metamethods - Gideros Forum

Lua: bitwise operators with new metamethods

n1cken1cke Maintainer
edited August 2016 in Step by step tutorials
With 2016.08 release we get full support of Lua 5.3 bitwise operators and integer division operator:
|  __bor  -- bitwise or (binary)
&  __band -- bitwise and (binary)
~  __bxor -- bitwise exclusive or (binary)
<< __shl  -- bitwise left shift (binary)
>> __shr  -- bitwise right shift (binary)
~  __bnot -- bitwise not (unary)
// __idiv -- integer division (binary)
All operators and their according metamethods are same as Lua 5.3 ones.
Example 1:
This function encodes any integer number (32 bits) to 4 chars to pass it over network later:
local function encodeInt(n)
	local t = {}
	local char = string.char
	t[1] = char(n >> 24 & 0xFF)
	t[2] = char(n >> 16 & 0xFF)
	t[3] = char(n >> 08 & 0xFF)
	t[4] = char(n >> 00 & 0xFF)
	return t:concat()
end
Example 2:
You can use new metamethods same way as old ones:
mt = {
	__bnot = function(t)
		local r = {}
		for i = 1, #t do r[i] = ~t[i] end
		return r
	end
}
t = {1, 2, 3, 4 ,5}
setmetatable(t, mt)
 
print(require"json".encode(~t)) --> [-2,-3,-4,-5,-6]
+1 -1 (+6 / -0 ) Share on Facebook

Comments

Sign In or Register to comment.