Hello,
No problem, your question makes perfect sense! It sounds like you're working towards a flexible and script-driven approach similar to Roblox Studio's Lua API. First, you need to decide on the high-level API that Lua scripts will interact with. Based on your example from Roblox Studio, you want a way to handle events and query input states. For handling events in Lua, you can provide a mechanism to connect Lua functions to input events. This means you'll need a way to register Lua functions that should be called when certain events occur, such as a key being pressed.
Given your existing structure with Keyboard, Mouse, and Input classes, you have a few options for exposing functionality to Lua:
Event Handling Wrapper:
Create a wrapper class or module in C++ that handles event registration and dispatching to Lua. This class will manage a list of Lua functions that are called when events occur.
For instance, you can have a class UserInputService that registers Lua callbacks for input events. You can then bind this class and its methods using sol2.
Direct Class Bindings:
Bind your Keyboard and Mouse classes directly to Lua. This will allow Lua scripts to query input states directly, but you'll need to handle event-driven behavior (like InputBegan) separately.
Example:
sol::state lua;lua.open_libraries(sol::lib::base);lua.new_usertype<Keyboard>("Keyboard", "isKeyDown", &Keyboard::isKeyDown);lua.new_usertype<Mouse>("Mouse", "isButtonDown", &Mouse::isButtonDown);
Event-Driven Interface:
Combine both approaches: Bind the Keyboard and Mouse classes for querying state, and create a separate UserInputService class to handle event registration and dispatch.
Example:
class UserInputService {
public:
void connect(std::function<void(const InputObject&)> callback) {
callbacks.push_back(callback);
}
void triggerEvent(const InputObject& inputObject) {
for (auto& callback : callbacks) {
callback(inputObject);
}
}
private:
std::vector<std::function<void(const InputObject&)>> callbacks;
};
// Bind the UserInputService to Lua
lua.new_usertype<UserInputService>("UserInputService",
"connect", &UserInputService::connect
);
Integrating with SDL2
You need to ensure that the UserInputService class can receive events from SDL2 and dispatch them to Lua. You'll need to connect SDL2 event handling to the triggerEvent method of UserInputService.
Example Lua Usage
In Lua, your script might look like this:
local UserInputService = require("UserInputService")
UserInputService:connect(function(inputObject)
if inputObject.UserInputType == "Keyboard" then
print(inputObject.KeyCode .. " was pressed")
end
end)
if UserInputService:IsKeyDown("A") then
-- Handle key press
end
Hope that helps!