lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Wed, Feb 22, 2012 at 11:56 AM, Jay Carlson <nop@nop.com> wrote:
> I see two interesting and broadly applicable patterns, and I'd
> probably use them both if I had them close at hand:
> Immutable tables: ft = final{k=2}

An alternative to preventing writes to tables (and not necessarily
better) is to check whether tables are changed after the fact.  FWIW,
I posted a proof-of-concept library based on debug hooks that checks
that function parameters with names postfixed by '_c' are unchanged
across function calls [1].  Example:

-- example.lua
local function g(a,b)
  b.x=1 -- ok
  table.sort(a) -- bad
end
local function f(a_c, b)
  return g(a_c, b)  -- tail call test
end
f({'b','a'}, {})

$ lua52 -ldebugconstcheck example.lua
lua52: ./debugconstcheck.lua:46: const variable mutated
stack traceback:
	[C]: in function 'error'
	./debugconstcheck.lua:46: in function <./debugconstcheck.lua:17>
	example.lua:8: in main chunk
	[C]: in ?

[1] http://lua-users.org/wiki/ImmutableObjects