Lua Host APIs
A host API is a table of functions that a host offers to guest code.
The host offers functions in a table
A table can hold functions. The host calls one here.
local api = {}
api.greet = function(name)
return "hello, " .. name
end
print(api.greet("Ana"))The guest receives the API in its environment
Load gives the guest chunk its own environment. That environment holds the API table.
local api = {}
api.greet = function(name)
return "hello, " .. name
end
local guest = load('print(api.greet("Ana"))', "guest", "t", { api = api, print = print })
guest()One API can offer several functions
The guest calls two API functions. Each result prints on its own line.
local api = {}
api.add = function(a, b)
return a + b
end
api.shout = function(word)
return string.upper(word)
end
local guest = load([[
print(api.add(3, 4))
print(api.shout("hi"))
]], "guest", "t", { api = api, print = print })
guest()Example
local count = 0
local api = {}
api.bump = function()
count = count + 1
end
api.read = function()
return count
end
local guest = load([[
api.bump()
api.bump()
print(api.read())
]], "guest", "t", { api = api, print = print })
guest()Key points
- Model: the host side here is modelled in Lua and no C code runs in this lesson.
- Host: a host is the program that runs guest code.
- Guest: guest code is code the host loads and runs.
- API: an API is a table of functions the guest may call.
- Environment: an environment is the table of names a chunk can see.
- Sharing: the host shares the API with the guest through the guest environment.
In this example, the host keeps a count and offers two API functions. The bump function adds one to the count. The read function returns the count. The guest calls bump twice and then prints the read result, so the output is 2.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Guest code needs to greet a user. Where does it get the greet function?