Peer-reviewed code snippets that anyone can edit
follow refactory on twitter
blog
feedback
A wiki for useful code snippets
Bugs? Suggestions?
38-107-191-111
create/login
options
RECENT
STUBS/REQUESTS
STARRED
ACTIVITY
ADD
VIEW
EDIT
FORK
Lua table proxy
lua
proxy
tables
Your work won't be attributed to you
because you aren't logged in.
Login using OpenID or an existing username, or create a username
(no email required) before posting.
Languages
Comma separated. Like
ruby, rails
or
java, swing
Keywords
Comma separated. Like
file, network
Mark as stub
Snippet
Wrap code in
[code=
language
][/code]
- Use
WikiText markup
outside of [code] tags
Lua has __index and __newindex metamethods, but not a __setindex or __changeindex. This way you don't know whether a key was already set and it's been changed. This is a simple solution that proxies a table so that exploits __newindex to set values to a subject instead of the proxy itself. This way when a key is set, it's always a "new index" in the proxy. [code=lua] proxy={} function proxy.new (subject) p={subject=subject} setmetatable(p, proxy) return p end function proxy:__index(key) print ("get", key) return rawget(self, 'subject')[key] end function proxy:__newindex(key, val) print ("set", key, val) subject = rawget (self, 'subject') subject[key] = val end [/code] Example usage: [code=lua] mytbl = {} container = proxy.new(mytbl) print(container.test) container.test = 'mytest' print(container.test) container.test = 'newtest' print(container.test) [/code] Notice "set" is being printed twice whenever a key is set, that's right what we wanted.
Log message
Human?
public snippets
This is a community-maintained collection of reusable code snippets.
Contribute something
without logging in, or improve existing contributions. All code is dedicated to the public domain unless otherwise specified.
stats
/
top contributers