Lua - Delegation and Tracing via Proxy Tables
Proxy table with a metatable can be used to perform delegation, tracing and debugging. In this chapter, we're covering them in details with examples.
Example - Delegation
When we need to forward certain actions to another object, this process is termed as delegation. In Lua, we can achieve the same using proxy table which will forward operation to another table to modify the argument or the result.
main.lua
-- delegate object
local delegate = {
greet = function(self, name)
return "Hello, " .. name .. "!"
end
}
-- prxy table
local proxy = {}
-- metatable for delegation
local metatableDelegation = {
__index = function(table, key)
return delegate[key]
end,
__call = function(table, ...)
return delegate.greet(target_object, ...)
end
}
-- set the metatable
setmetatable(proxy, metatableDelegation)
-- call greet method on proxy
-- prints Hello, Bob!
print(proxy.greet(proxy_object, "Bob"))
-- call proxy as a method
-- prints Hello, Charlie!
print(proxy("Charlie"))
Output
When we run the above program, we will get the following output−
Hello, Bob! Hello, Charlie!
Example - Tracing and Debugging
Tracing is a very important aspect of debugging. We can utilize a proxy table to trace all access and modification to underlying table without modifying the original table.
main.lua
-- actual table
local actualTable = {}
-- proxy table
local proxy = {}
-- metatable to trace each access/modification
local metatableTracing = {
__index = function(table, key)
print("Key accessed:", key)
return actualTable[key]
end,
__newindex = function(t, key, value)
print("Setting Key:", key, "With value:", value)
actualTable[key] = value
end
}
setmetatable(proxy, metatableTracing)
-- set a value to the table via proxy
proxy.count = 1
-- get a value from table via proxy
local value = proxy.count
-- prints 1
print(value)
Output
When we run the above program, we will get the following output−
Setting Key: count With value: 1 Key accessed: count 1
Advertisements