Roblox studio how to detect key inputs? - lua

I am trying to make a GUI that toggles on key input and i have already looked at the roblox wikipedia and a question that is supposedly what i am asking however it doesn't seem to work. Roblox Studio - Key Toggle for GUI
I have got no code because i completely don't understand ContextActionService so sorry.

In order to toggle a GUI on and off, you just need a reference to the UIElement and you can set its Parent value. ContextActionService:BindAction just allows you to bind the action to some kind of input.
Here's a simple example that is a little more explicit than the one in the linked question.
Make a LocalScript in StarterPlayer > StarterCharacterScipts, add this code
-- make a simple GUI to show off
local targetGui = Instance.new("ScreenGui")
local label = Instance.new("TextLabel", targetGui)
label.Text = "Hello World"
label.Position = UDim2.new(0, 0, 0, 0)
label.Size = UDim2.new(0, 200, 0, 30)
-- choose where to make the gui
local targetParent = game.Players.LocalPlayer.PlayerGui
-- make a function for handling key presses
local function handleKeyPress(actionName, inputState, inputObj)
-- DEBUG : show the information for this keypress
print("Handle Key Press")
print("Action Name : ", actionName)
print("Input State : ", inputState)
print("Input Obj - KeyCode : ", inputObj.KeyCode)
print("")
if inputState == Enum.UserInputState.End then
if targetGui.Parent then
targetGui.Parent = nil
else
targetGui.Parent = targetParent
end
end
end
-- connect that function to ContextActionService
local createDedicatedButtonOnMobile = false
game.ContextActionService:BindAction("toggleGui", handleKeyPress, createDedicatedButtonOnMobile, Enum.KeyCode.R)
Now whenever you press R it will parent or unparent the gui element. Now you've got a toggle.
BindAction is a very flexible function, so there isn't just one way to do this stuff. In this example, when you press R, you will see handleKeyPress fire a few times. Its output should look something like this :
Handle Key Press
Action Name : toggleGui
Input State : Enum.UserInputState.Begin
Input Obj - KeyCode : Enum.KeyCode.R
Handle Key Press
Action Name : toggleGui
Input State : Enum.UserInputState.End
Input Obj - KeyCode : Enum.KeyCode.R
This is because a key press has two states, one when you press the key down, and one when you lift the key up. The example function listens for when you lift up your finger before executing the toggle.
Hope this helps, let me know if you are still stuck.

Related

How does this function keep track of clicks?

On the "Thinking in Compose" page I don't get this code, how does $clicks keep track of number of clicks?
#Composable
fun ClickCounter(clicks: Int, onClick: () -> Unit) {
Button(onClick = onClick) {
Text("I've been clicked $clicks times")
}
}
I'm learning Kotlin at the same time as Compose, so I get puzzled all the time.
It's omitted in that example but it should store the click-count in a MutableState<T> wrapped with remember
var clickCount by remember { mutableStateOf(0)}
ClickCounter(clicks = clickCount, onClick = {clickCount += it})
For real real real beginner like me, let me add my comment and code.
When the ClickCounter composable is called we need to pass two parameters.
To 'clicks', we pass initial value 0 which will be changed everytime we click the button. Also the initial value need to be 'remembered' and tracked for further changes. So we create new variable using 'mutableStateOf' function inside 'remember' function.
To 'onClick', we need to pass function which adds 1 everytime the button is clicked.
As a caller of the ClickCounter composable, I made a simple preview composable as below.
#Preview(showBackground = true)
#Composable
fun ClickCounterPreview(){
var clicks by remember { mutableStateOf(0) }
// We call ClickCounter composable passing two parameters.
ClickCounter(clicks = clicks, onClick = { clicks += 1 })
}

Button that executes textbox contents roblox

I'm trying to make a gui with a textbox where you type in for example print("Hello world!") you click a button and it executes it but I can't figure out the execute part I've tried this so far:
local ScrTxt = script.Parent.Parent.TextBox
local Button = script.Parent
Button.MouseButton1Click:Connect(function()
print(ScrTxt.Text)
end)
To execute a string as code, LoadStringEnabled must be enabled
Then, you can do this:
local ScrTxt = script.Parent.Parent.TextBox
local Button = script.Parent
Button.MouseButton1Click:Connect(function()
loadstring(ScrTxt.Text)()
end)

How do I make an if statement that check if a part has been clicked (roblox lua)

How do I make an if statement check if a part has been clicked on?
Also it's not a gui
Here is some of the code I wrote:
local chat = game.Workspace.Dummy1.Head.Dialog
local Menu = {"pizza","fries","hamburger"}
local Item = math.random(1,#Menu) -- chooses random Item from the table
chat.InitialPrompt = (Menu[Item]) -- says random item
local PizzaButton = game.Workspace.PizzaButton -- a variable for the button
local FriesButton = game.Workspace.FriesButton -- a variable for the button
local BurgerButton = game.Workspace.BurgerButton -- a variable for the button
if chat.InitialPrompt == "pizza" then -- checks what have random item has been chosen
print("Pizza has been chosen")
if -- Here I want to check if a button has been clicked
elseif chat.InitialPrompt == "fries" then -- checks what have random item has been chosen
print("Fries has been chosen")
if -- Here I want to check if a button has been clicked
elseif chat.InitialPrompt == "hamburger" then -- checks what have random item has been chosen
print("Burger has been chosen")
if -- Here I want to check if a button has been clicked
else
print("Error")
end
This is the best I could explain it 😅
This is simple, you can add a bool value inside the button parts and name it clicked. And set the value to true when the button is first clicked.
if chat.InitialPrompt == "pizza" then -- checks what have random item has been chosen
print("Pizza has been chosen")
-- code inserted here
if PizzaButton.clicked.Value == true then
-- The Button is already clicked
else
PizzaButton.clicked.Value = true
-- Actions to take on first click
end
elseif --do the same for all other buttons
With what the guy above me said you should also add this to reduce the lines of code
local chat = game.Workspace.Dummy1.Head.Dialog
local Menu = {"Pizza","Fries","Hamburger"}
local Item = math.random(1,#Menu)
chat.InitialPrompt = (Menu[Item])
local PizzaButton = game.Workspace.PizzaButton
local FriesButton = game.Workspace.FriesButton
local BurgerButton = game.Workspace.BurgerButton
if table.find(Menu,chat.InitialPrompt) then
print(chat.InitialPrompt.." has been chosen")
else
print("Error")
end

PySimpleGui: How to add values from one listbox to another

So I've been looking for an answer to this for quite a while. Apologies if I'm just overlooking something here.
I want to create two listboxes where you can move the values from one listbox into another listbox, creating your own order for those values. This is because I'm trying to make a GUI for an API, and the order of the values will ultimately determine the order of dimension/metric headers, which is extremely important.
This was the approach I tried to take to achieve this, however, it appears the TEST object just overwrites its list everytime the "Add" button is pressed, whereas I want it to append:
import PySimpleGUI as sg
list1 = ["a", "b", "c"]
layout = [[sg.Text("Demo")],
[sg.Listbox(values=list1, size=(30,6), enable_events=True, key="-LIST-"), sg.Button("Add", enable_events=True, key="-BUTTON-"), sg.Listbox(values=[], size=(30,6), key="-LIST2-")],
[sg.Cancel("Exit")]]
window = sg.Window("Beta", layout=layout, background_color="#272533", size=(650, 450))
while True:
event, values = window.read()
if event == "Exit" or event == sg.WIN_CLOSED:
break
if event == "-BUTTON-":
TEST = []
TEST.append(values["-LIST-"])
window["-LIST2-"].update(TEST)
print(TEST)
window.close()
Thank you Jason, I managed to set up two listboxes such that you can move items from one box to another and thereby create whatever order of items you want by using get_indexes().
Basically I started with an empty list, then used get_indexes() to find the index of the value a user determines in the initial list. I then append that value onto the empty list using the pop function so it is deleted from the initial list. Then I had to update both windows so the indexes would update for when the user moves the next value.
Here's the code I used to get it to work. It's probably not the most beautiful or efficient (I'm quite new to python) but it does work! If there are any suggestions for how to make it more succinct they would be appreciated!
import PySimpleGUI as sg
list1 = ['a', 'b', 'c']
list2 = []
layout = [[sg.Text("Demo")],
[sg.Listbox(values=list1, size=(30,6), enable_events=True, key="-LIST-"), sg.Button("Add", enable_events=True, key="-BUTTON-"), sg.Button("Remove", enable_events=True, key="-BUTTON2-"), sg.Listbox(values=list2, size=(30,6), key="-LIST2-")],
[sg.Cancel("Exit")]]
window = sg.Window("Beta", layout=layout, background_color="#272533", size=(650, 450))
while True:
event, values = window.read()
if event == "Exit" or event == sg.WIN_CLOSED:
break
if event == "-BUTTON-":
INDEX = int(''.join(map(str, window["-LIST-"].get_indexes())))
list2.append(list1.pop(INDEX))
window["-LIST2-"].update(list2)
window["-LIST-"].update(list1)
if event == "-BUTTON2-":
INDEX = int(''.join(map(str, window["-LIST2-"].get_indexes())))
list1.append(list2.pop(INDEX))
window["-LIST2-"].update(list2)
window["-LIST-"].update(list1)
window.close()

Corona composer.gotoScene() does not reset my scene

I am pretty new to Corona. I have a button that triggers the following code:
local options =
{
effect = "fade",
time = 400,
params = {
loadFromFile = true,
fileName = "level1",
level = levelParams
}
}
composer.gotoScene( "view1", options)
When I finish the level and click this button again, the "view1" scene is in the same state. How do I reset it quickly? Like creating an entirely new scene object?
I tried using composer.removeScene() and purge, but nothing happens. Even non-graphic element stay the same, like scores and stuff.
Any ideas?
Thanks.
Regards,
Serban
You create objects in
function scene:create( event )
then if you want them to change everytime you go away and come back, you should manipulate your objects under:
function scene:show( event )
There is an example under welcome screen>interface>composer in Corona SDK.

Resources