Skip to content

Lua API: 1. Inputs: Mouse and Keyboard

MCUmbrella edited this page Nov 24, 2023 · 1 revision

Mouse

Static functions

getX, getY

Get the position of the mouse cursor (based on the top left corner of the window). After the cursor leaves the window, the two values will no longer change.

Return: Integer starting from 0. X increases as the cursor is moved to the right and Y increases as the cursor is moved to the bottom.

Example:

mouseX = Mouse.getX()
mouseY = Mouse.getY()

(...)Holding

where "(...)" can be:

  • l: left button
  • m: middle button
  • r: right button
  • x1: extended button 1
  • x2: extended button 2

Check if a mouse button is held down.

Return: true if the button is held down, false otherwise.

Example:

if Mouse.lHolding() then
  Runtime.log("LMB holding")
end

(...)Pressed

The difference between this and the "holding" function is that it only returns true on the first tick that the button is held down, until the button is released and pressed again.

Example:

if Mouse.x1Pressed() or Mouse.x2Pressed() then
  Runtime.log("Extended buttons? Nice")
end

wheelUp, wheelDown, wheelLeft, wheelRight

Check if the mouse wheel has scrolled in the specified direction.

NOTICE: Scrolling left and right can be simulated by two-finger swiping left or right on the touchpad (with the computer and the system software working well together).

Return: true if so, false otherwise.

Example:

if Mouse.wheelUp() then
  Runtime.log("Scrollling up")
  -- TODO: page scrolling logics
end

hidden

Check if the system cursor is hidden in the window. Can also be used to hide/show system cursor.

Parameter:

  • Boolean state (optional): Whether to hide or show system cursor. If the parameter is not present, the hide state remains unchanged.

Return: The current hide state of the system cursor.

Example:

--[[
  The following code switches the hide state of system cursor when the user
  presses the middle mouse button.
]]--

if Mouse.mPressed() then
  Runtime.log("Switching cursor hide state")
  Mouse.hidden(not Mouse.hidden())
end

Keyboard

Static functions

holding

Check if a key is held down.

Parameter:

  • Number scancode: The SDL scancode of the key to be checked. See "SDL_scancode.h" in SDL sources or SDL scancode lookup table

Return: true if so, false otherwise.

Example:

if Keyboard.holding(7) -- The "D" key
then
  Runtime.log("Player walking right")
end

pressed

Returns true on the first tick that the key is held down, until the key is released and pressed again.

Parameter: same as above.

Return: true if so, false otherwise.

Example:

if Keyboard.pressed(44) -- The SPACE key
then
  Runtime.log("Player jump")
end

repeated

Check if a key is repeated.

Parameter: same as above.

Return: Continuously true after the key has been held down for a few ticks, until it is released.

Example:

-- Hold ESC to exit
if Keyboard.repeated(41)
then
  Runtime.log("Exiting")
  Engine.stop()
end