Imported from ../lua-3.1.tar.gz.
[lua.git] / etc / setfallback.lua
blob783b8667d73d5346a35a3fa861c76cdcb0b8460c
1 --------------------------------------------------------------
2 -- Definition of "setfallback" using tag methods
3 -- (for compatibility with old code)
4 --------------------------------------------------------------
7 -- default fallbacks for each event:
8 local defaults = {
9 gettable = function () error('indexed expression not a table') end,
10 settable = function () error('indexed expression not a table') end,
11 index = function () return nil end,
12 getglobal = function () return nil end,
13 arith = function () error('number expected in arithmetic operation') end,
14 order = function () error('incompatible types in comparison') end,
15 concat = function () error('string expected in concatenation') end,
16 gc = function () return nil end,
17 ['function'] = function () error('called expression not a function') end,
18 error = function (s) write(_STDERR, s, '\n') end,
22 function setfallback (name, func)
24 -- set the given function as the tag method for all "standard" tags
25 -- (since some combinations may cause errors, use call to avoid messages)
26 local fillvalids = function (n, func)
27 call(settagmethod, {0, n, func}, 'x', nil)
28 call(settagmethod, {tag(0), n, func}, 'x', nil)
29 call(settagmethod, {tag(''), n, func}, 'x', nil)
30 call(settagmethod, {tag{}, n, func}, 'x', nil)
31 call(settagmethod, {tag(function () end), n, func}, 'x', nil)
32 call(settagmethod, {tag(settagmethod), n, func}, 'x', nil)
33 call(settagmethod, {tag(nil), n, func}, 'x', nil)
34 end
36 assert(type(func) == 'function')
37 local oldfunc
38 if name == 'error' then
39 oldfunc = seterrormethod(func)
40 elseif name == 'getglobal' then
41 oldfunc = settagmethod(tag(nil), 'getglobal', func)
42 elseif name == 'arith' then
43 oldfunc = gettagmethod(tag(0), 'pow')
44 foreach({"add", "sub", "mul", "div", "unm", "pow"},
45 function(_, n) %fillvalids(n, %func) end)
46 elseif name == 'order' then
47 oldfunc = gettagmethod(tag(nil), 'lt')
48 foreach({"lt", "gt", "le", "ge"},
49 function(_, n) %fillvalids(n, %func) end)
50 else
51 oldfunc = gettagmethod(tag(nil), name)
52 fillvalids(name, func)
53 end
54 return oldfunc or rawgettable(%defaults, name)
55 end