Last active
May 31, 2020 08:02
-
-
Save Zeta611/704e1a8f1d1ce58578423f044b03bd7f to your computer and use it in GitHub Desktop.
[Lua sample] Simple demo of a Lua code #demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Use a builder to safely make objects | |
function build_complex(r, i) | |
return {real = r, img = i} | |
end | |
-- Accessing a value with a key | |
complex = build_complex(3, 4) | |
assert(complex["real"] == complex.real) | |
print(complex.real) | |
-- Calling a "member function" | |
function _conjugate(c) | |
c.img = -c.img | |
end | |
complex.conjugate = _conjugate | |
complex.conjugate(complex) | |
complex:conjugate() | |
print(complex.img) | |
-- Operator overloading via a metatable | |
mt = {} | |
mt.__add = function(c1, c2) | |
return build_complex(c1.real + c2.real, c1.img + c2.img) | |
end | |
function build_complex(r, i) | |
local ret = {real = r, img = i} | |
setmetatable(ret, mt) | |
return ret | |
end | |
complex = build_complex(complex.real, complex.img) | |
print((complex + complex).real) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment