· 6 years ago · Dec 14, 2019, 05:12 AM
1
2if not commands then
3 error( "Cannot load command API on normal computer", 2 )
4end
5
6local native = commands.native or commands
7
8local function collapseArgs( bJSONIsNBT, ... )
9 local args = table.pack(...)
10 for i = 1, #args do
11 local arg = args[i]
12 if type(arg) == "boolean" or type(arg) == "number" or type(arg) == "string" then
13 args[i] = tostring(arg)
14 elseif type(arg) == "table" then
15 args[i] = textutils.serialiseJSON( arg, bJSONIsNBT )
16 else
17 error( "Expected string, number, boolean or table", 3 )
18 end
19 end
20
21 return table.concat(args, " ")
22end
23
24-- Put native functions into the environment
25local env = _ENV
26env.native = native
27for k,v in pairs( native ) do
28 env[k] = v
29end
30
31-- Create wrapper functions for all the commands
32local tAsync = {}
33local tNonNBTJSONCommands = {
34 [ "tellraw" ] = true,
35 [ "title" ] = true
36}
37
38local command_mt = {}
39function command_mt.__call(self, ...)
40 local meta = self[command_mt]
41 local sCommand = collapseArgs( meta.json, table.concat(meta.name, " "), ... )
42 return meta.func( sCommand )
43end
44
45function command_mt.__tostring(self)
46 local meta = self[command_mt]
47 return ("command %q"):format("/" .. table.concat(meta.name, " "))
48end
49
50function command_mt.__index(self, key)
51 local meta = self[command_mt]
52 if meta.children then return nil end
53 meta.children = true
54
55 local name = meta.name
56 for _, child in ipairs(native.list(table.unpack(name))) do
57 local child_name = { table.unpack(name) }
58 child_name[#child_name + 1] = child
59
60 self[child] = setmetatable({ [command_mt] = {
61 name = child_name,
62 func = meta.func,
63 json = meta.json
64 } }, command_mt)
65 end
66
67 return self[key]
68end
69
70for _, sCommandName in ipairs(native.list()) do
71 if env[ sCommandName ] == nil then
72 local bJSONIsNBT = tNonNBTJSONCommands[ sCommandName ] == nil
73 env[ sCommandName ] = setmetatable({ [command_mt] = {
74 name = { sCommandName },
75 func = native.exec,
76 json = bJSONIsNBT
77 } }, command_mt)
78
79 tAsync[ sCommandName ] = setmetatable({ [command_mt] = {
80 name = { sCommandName },
81 func = native.execAsync,
82 json = bJSONIsNBT
83 } }, command_mt)
84 end
85end
86env.async = tAsync