Skip to content
Snippets Groups Projects
Verified Commit 748951a2 authored by Vladimír Čunát's avatar Vladimír Čunát
Browse files

modules: change the "indexing" syntax sugar for C modules

In particular, throw errors when used in weird ways,
instead of the usual "return nil" semantics.
That might be surprising to some lua users.
parent fc12d433
Branches
Tags
1 merge request!797lua light userdata
......@@ -5,6 +5,8 @@ Improvements
------------
- DNS-over-HTTPS: answers include `access-control-allow-origin: *` (!823)
- support named AF_UNIX stream sockets for the http module (again)
- lua tables for C modules are more strict by default, e.g. `nsid.foo`
will throw an error instead of returning `nil` (!797)
Bugfixes
--------
......
......@@ -179,7 +179,8 @@ function modules_create_table_for_c(kr_module_ud)
return
end
local module = {}
_G[ffi.string(kr_module.name)] = module
local module_name = ffi.string(kr_module.name)
_G[module_name] = module
--- Construct lua functions for properties.
if kr_module.props ~= nil then
......@@ -229,19 +230,33 @@ function modules_create_table_for_c(kr_module_ud)
--- Add syntactic sugar for get() and set() properties.
--- That also "catches" any commands like `moduleName.foo = bar`.
setmetatable(module, {
__index = function (t, k)
local v = rawget(t, k)
if v then return v
elseif rawget(t, 'get') then return t.get(k)
end
end,
__newindex = function (t, k, v)
local old_v = rawget(t, k)
if not old_v and rawget(t, 'set') then
t.set(k..' '..v)
end
local m_index, m_newindex
local get_f = rawget(module, 'get')
if get_f ~= nil then
m_index = function (_, key)
return get_f(key)
end
else
m_index = function ()
error('module ' .. module_name .. ' does not support indexing syntax sugar')
end
end
local set_f = rawget(module, 'set')
if set_f ~= nil then
m_newindex = function (_, key, value)
-- This will produce a nasty error on some non-string parameters.
-- Still, we already use it with integer values, e.g. in predict module :-/
return set_f(key .. ' ' .. value)
end
else
m_newindex = function ()
error('module ' .. module_name .. ' does not support assignment syntax sugar')
end
end
setmetatable(module, {
-- note: the two functions only get called for *missing* indices
__index = m_index,
__newindex = m_newindex,
})
end
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment