Sign in to follow this  

[Tutorial] Make more Object-Oriented scripts

3 posts in this topic

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 (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)
		-- 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: ""   "..tostring(properties.panelState))
		end = function()
			printConsoleText("INFO test")
		return methods

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

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



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)

function a:give()
	return self.text

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