lua-users home
lua-l archive

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


> I'm looking to find a way to prevent new values from being entered
> into a table. I tried the read-only table approach from PIL
> (http://www.lua.org/pil/13.4.5.html) which works as advertised.
> However, I can still insert values like:
>
> table.insert(days, "Frankday")
>
> Any suggestions?

That's a pretty odd problem, I have a solution for you. I'm not sure that it is the "best" solution however.

Inside your readonly function (as seen in PIL), you can put:

    table.insert(readonly, proxy)

Below put this somewhere in one of your main chunks.

    readonly = { } -- Contains all readonly tables.

    do
      local insert = table.insert;
      function table.insert(t, v)
        for _, value in pairs(readonly) do
          if t == value then
            error("attempt to modify a readonly table", 2);
            return;
          end;
        end;
        insert(t, v);
      end;
    end;

This will cause an error:

    table.insert(proxy, "hi");

Good Luck,

-Patrick Donnelly

"One of the lessons of history is that nothing is often a good thing to do and always a clever thing to say."

-Will Durant