Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- factorial.lua:
- function fact (n)
- if n == 0 then
- return 1
- else
- return n * fact(n-1)
- end
- end
- -- print("enter a number:")
- -- a = io.read("*number") -- read a number
- -- print(fact(a))
- -- test1.lua:
- dofile('factorial.lua')
- local x = {1, 2, 3, 4, 5, value = 3}
- local mt = {
- __add =
- function (lhs, rhs) -- "add" event handler
- return { value = lhs.value + rhs.value }
- end,
- __mul =
- function (lhs, rhs) -- "add" event handler
- return { value = lhs.value * rhs.value }
- end
- }
- setmetatable(x, mt) -- use "mt" as the metatable for "x"
- local y = x + x
- print(y.value)
- local z = x * x
- print(fact(z.value))
- -- test2.lua:
- -- Creates 'vector' table with a "vector space" metatable such as it assigns the vector_metatable metatable to every value set on 'vector'. The vector_metatable allows sum and dot product of vectors of same size. Only for testing purposes.
- local vector = {}
- local vector_metatable = {
- __add =
- function (lhs, rhs)
- local res = {}
- for i=1,table.maxn(lhs) do
- res[i] = lhs[i] + rhs[i]
- end
- return res
- end,
- __mul =
- function (x, y)
- if type(x) == 'table' then
- lhs = y
- rhs = x
- else if type(y) == 'table' then
- lhs = x
- rhs = y
- end
- end
- if type(lhs) == 'table' then
- local sum = 0
- for i=1,table.maxn(rhs) do
- sum = sum + lhs[i] * rhs[i]
- end
- return sum
- else
- local res = {}
- for i=1,table.maxn(rhs) do
- res[i] = lhs * rhs[i]
- end
- return res
- end
- end
- }
- local vspace_metatable = {
- __newindex =
- function (t, key, value)
- setmetatable(rawset(t, key, value)[key], vector_metatable)
- end
- }
- setmetatable(vector, vspace_metatable)
- vector.x = {1, 2, 3, 4, 5}
- vector.z = {3, 7, 5, 1, 0}
- local y = vector.x * vector.z
- if type(y) == 'table' then
- for i=1,table.maxn(y) do
- print(y[i])
- end
- else
- print(y)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement