To make a vote: define a title, some vote options and a callback function that will process the vote result.
local voteTitle = "Set difficulty to.."
local voteOptions = {"Easy", "Intermediate", "Hard"}
local voteCallback = function ( t )
-- Code in this function will run after the vote finishes
-- TODO: Write callback code
end
The vote callback has a parameter
t. It’s a table that contains all data related to the vote.
Here's an example of what
t looks like, if 1 person votes for the second option.
args:
callback = function: 0xe4448f48
options:
1 = Easy
2 = Intermediate
3 = Hard
results:
2 = 1
title = Set game difficulty to...
voters = 1
votes = 1Let's update the vote callback function so it uses the data in
t.results to calculate the winning vote option and display the result.
local voteCallback = function ( t )
-- Calculate winning option
local winningOptionName
local winningOptionVotes = 0
for key, votes in pairs( t.results ) do
if votes > winningOptionVotes then
winningOptionName = voteOptions[ key ]
winningOptionVotes = votes
end
end
-- Display the result
local str
if not winningOptionName then
str = "Vote results: No option won because no one voted!"
else
str = "Vote results: Game difficulty set to \"" .. winningOptionName .. "\""
end
ULib.tsay( _, str ) -- Show str to players in chat and console
ulx.logString( str ) -- Log str in logfile
Msg( str .. "\n" ) -- Show str in the server console
end
The title, options and callback are defined. A simple ULX command can be created to trigger the vote.
function ulx.myvote( calling_ply )
if ulx.voteInProgress then
ULib.tsayError( calling_ply, "There is already a vote in progress. Please wait for the current one to end.", true )
return
end
ulx.doVote( voteTitle, voteOptions, voteCallback ) -- Trigger the vote
ulx.fancyLogAdmin( calling_ply, "#A started a vote (#s)", voteTitle )
end
local myvote = ulx.command( "Voting", "ulx myvote", ulx.myvote, "!myvote" )
myvote:defaultAccess( ULib.ACCESS_ADMIN )
myvote:help( "Starts my vote." )
You can now append the code that changes the server difficulty to the vote callback.
I have attached a working example that you can pop in your server’s
addons/ directory. You can download it below.