Lua base functions Lua bc (big number) functions Lua bit manipulation functions Lua coroutine functions Lua debug functions Lua io functions Lua LPEG library Lua math functions Lua os functions Lua package functions Lua PCRE regular expression functions Lua script extensions Lua string functions Lua syntax Lua table functions Lua utilities.
![]()
The reference manual is the official definition of the Lua language.
For a complete introduction to Lua programming, see the bookProgramming in Lua.
This manual is also available as a book:
Lua 5.1 Reference Manualby R. Ierusalimschy, L. H. de Figueiredo, W. Celes
Buy a copyof this book andhelp to supportthe Lua project.
start·contents·index·errata·other versions·português·español·deutsch
Copyright © 2006–2012 Lua.org, PUC-Rio.Freely available under the terms of theLua license.
Contents
Index
Last update:Mon Aug 26 22:33:54 UTC 2019
This article describes a technique for making a table read-only via metamethods in Lua 5.0/5.1 (for background on metamethods see the MetamethodsTutorial). The approach will only prevent the inadvertent modification of any member of a read-only table.
We can define read-only (constant) tables like this:
if we define the
readonlytable helper functions as follows:
Note that
readonlytable does not return the table originally passed to it but rather a proxy table. The proxy table is given a metatable with the metamethods __index and __newindex to ensure that the proxy table values never change. Setting the __metatable metamethod prevents tampering with the metatable itself--the client cannot obtain nor change the metatable via getmetatable and setmetatable functions.
Now if we try to modify any member of
Directions we will get an error.
![]()
Although members of the read-only table cannot be changed, it is still possible to modify members of members of read-only tables (unless they too are explicitly made read-only tables):
Also,
rawset() and table.insert can still be used to directly modify a read-only table:
![]()
If you really need to avoid that, you could implement the read-only table in C.
Furthermore, this method of creating read-only tables interferes with
pairs , ipairs , next , the # operator, and other forms of table iteration. For example,
See also GeneralizedPairsAndIpairs for ways to handle that.
Original author: KevinBaca
See Also
edit · history Last edited March 8, 2016 2:26 pm GMT (diff) ![]() Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
March 2023
Categories |