Ways to simplify this code?

That actually is very clean code.

TNLO approved. :vulcan_salute:

That’s honestly a pretty rare thing to come across.

Not really a simplification, but I can offer an optimization instead.

Do note that this is only intended as a performance optimization when using --!native. On current Luau builds, the benefit comes from native compilation; without it, this pattern is generally not worthwhile for performance.

Yeah, it’s a bit hacky, but I figured I’d share it anyway.

--!strict
--!optimize 2
--!native
local SetProperty = select(2,xpcall(function():()
	(game::any)[nil]=nil
end,function():()
	return debug.info(2,"f")
end))::(ins:Instance,prop:string,val:any)->()

local GetProperty = select(2,xpcall(function():()
	return (game::any)[nil]
end,function():()
	return debug.info(2,"f")
end))::(ins:Instance,prop:string)->any

local GetService = GetProperty(game,"GetService")::(DataModel:DataModel,service:string)->Instance

local UserInputService = GetService(game,"UserInputService")::UserInputService
local InputBegan = GetProperty(UserInputService,"InputBegan")::RBXScriptSignal
local Connect = InputBegan.Connect::(RBXScriptSignal,func:(...any)->...any)->RBXScriptConnection
local Once = InputBegan.Once::(RBXScriptSignal,func:(...any)->...any)->RBXScriptConnection

local InputObject_Get: InputObject_KeyCode&InputObject_UserInputState&InputObject_UserInputType&InputObject_any
type InputObject_KeyCode = (obj:InputObject,"KeyCode")->Enum.KeyCode
type InputObject_UserInputState = (obj:InputObject,"UserInputState")->Enum.UserInputState
type InputObject_UserInputType = (obj:InputObject,"UserInputType")->Enum.UserInputType
type InputObject_any = (obj:InputObject,property:string)->any

local InputBegan_Func = function(input:InputObject,gameProcessed:boolean):()
	if gameProcessed then return end
	local func = beginState[InputObject_Get(input,"KeyCode")]
	if not func then return end
	func()
end

Once(InputBegan,function(input:InputObject,gameProcessed:boolean):()
	xpcall(function():()
		return (input::any)[nil]
	end,function():()
		InputObject_Get = debug.info(2,"f")::typeof(InputObject_Get)
	end)

	Connect(InputBegan,InputBegan_Func)
	InputBegan_Func(input,gameProcessed)
end)

Connect(GetProperty(UserInputService,"InputEnded"),function(input:InputObject,gameProcessed:boolean)
	if gameProcessed then return end
	local func = endState[InputObject_Get(input,"KeyCode")]
	if not func then return end
	func()
end)
1 Like