Sign in to follow this  
Povka*

[Tutorial] Make more Object-Oriented scripts

Recommended Posts

Took my code snippet how code should be more object-oriented in Lua with a simple example (it's a demo). Run script in your server and press "F7" chat box will print 2 messages.

The idea explained in https://www.lua.org/pil/16.4.html (but I wrote it myself :P)

--declaration of mine ClientUiManager "class"
local ClientUIManager = {
	newInstance = function(playerName) 
	
		local properties = {
			panelState = false,
			playerName = playerName,
			textColor = {255, 102, 0}
		}
		
		-- define internal functions
		
		local function printConsoleText(text)
			outputChatBox(text, properties.textColor[1], properties.textColor[2], properties.textColor[3], true)
		end
		
		-- define all functions that will be used to access properties or other logic
		local methods = {}
		
		methods.handlePlayerPressEvent = function (button, press)
			if (press and button == "F7") then
				properties.panelState = not properties.panelState
				printConsoleText("You pressed the "..button.." key!  State: "..properties.playerName.."   "..tostring(properties.panelState))
				methods.info()
			end
		end
		
		methods.info = function()
			printConsoleText("INFO test")
		end
	
		return methods
	end
}


local playerName = getPlayerName(getLocalPlayer());
local clientUIManager = ClientUIManager.newInstance(playerName)

addEventHandler("onClientKey", getRootElement(), clientUIManager.handlePlayerPressEvent)

Result:

example.png.72d4140ed50e1914f2309ad7ef1033c0.png

Share this post


Link to post
Share on other sites

The way you use is simply using functions inside a table. It could be considered OOP, but using metatables is the official way in Lua. Also, your table is a local variable, just to point out.

 

An example of using metatable method:

a = {}
a_mt = {__index = a}

function a:create(test)
	local b = {}
	b.text = test
	return setmetatable(b,a_mt)
end

function a:give()
	return self.text
end

local c = a:create("Hey")
c:give() -- This returns the string "Hey"

As you can see, in this method you are able to use variable:functionname(), unlike yours.

While both are fine, I personally recommend this one.

 

//Edit: To be fair, I don't know which is the official one. For me it seemed this one, but I don't know.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this