Module Lock

Protects tables against accidential read/write.

Module Status: Experimental 2020-10-31.

Usage:

    local Lock = require('__eradicators-library__/erlib/lua/Lock')()
    

Functions

auto_lock(tbl, name[, passphrase[, err_write[, err_read]]]) Prevents accidential writing to tables.
is_locked(tbl) Detects if a table was locked by this module.
remove_lock(tbl) Removes any locks created by this module.


Functions

auto_lock(tbl, name[, passphrase[, err_write[, err_read]]])
Prevents accidential writing to tables. Intended mainly to detect leaking global access when you forgot to type "local" again. It is called "Auto"-Lock because it re-locks any key as soon as it becomes nil, even if it had a value before.

Note: You have to manually remove this after your done if you use it in any of the shared loading stages (data, settings).

Parameters:

  • tbl table The table to apply the lock to.
  • name string The table's name. Used for error messages.
  • passphrase string → usage examples are below. (optional)
  • err_write function A custom error handler. f(tbl,key,value) (optional)
  • err_read function A custom error handler. f(tbl,key) (optional)

Returns:

    table The now locked table tbl.

Usage:

    -- Apply the lock to any table.
    -- For this example we'll apply it to the global environment.
    Lock.auto_lock(_ENV,'Global Environment','MyPassword')
    
    -- Accidential writing of ney keys will fail.
    _ENV.A_New_Key = 'A new value!'
    > Error! Global Environment is write locked!
    
    -- Accidential read will also fail.
    if _ENV.A_New_Key then print('not ok') end
    > Error! Global Environment is read locked!
    
    -- Use __has_key instead.
    if not _ENV.__has_key('A_New_Key') then print('ok') end
    > ok
    
    -- The passphrase function allows you to explicitly circumvent the lock.
    MyPassword('A_New_Key','A new value!')
    print(_ENV.A_New_Key)
    > A new value!
    
    -- Keys that become nil will become locked again.
    _ENV.A_New_Key = nil
    if _ENV.A_New_Key then print('not ok') end
    > Error! Global Environment is read locked!
    
    -- You can declare a key global without assigning a value.
    MyPassword('Another_New_Key')
    if not Another_New_Key then print('ok this time!') end
    > ok this time!
    
    -- It'll have the default value of boolean false.
    if (Another_New_Key == false) then print('I got it.') end
    > I got it.
    
    
is_locked(tbl)
Detects if a table was locked by this module.

Parameters:

Returns:

    boolean
remove_lock(tbl)
Removes any locks created by this module. Will error if you try to remove any other kind of lock or metatable.

Parameters:

generated by LDoc 1.4.6 Last updated 2021-09-10 19:51:19