Post functions that you have found/created that would be useful for plugin developers using the LUA language.
Alternative threads can be created and maintained by users that program in any of the other three languages.
Rules:
Example:
- DO NOT POST UNTESTED CODE!
- Do not spam
- Do not go offtopic
- If you post a function which is not created by yourself, you have to give the original author credits
- And also if you use a function in your plugin that you copied from this topic, don't forget to give the original author credits
printf
Example Usage:Code:function printf(...) print(string.format(...)) end
This is a copy of a thread I originally contributed to on another modification. The thread ended up at 452 pages, I hope we can achieve similar standards here.Code:printf("Hello %s", username)
Beginning of thread:
-----------------------------------------------------------------------------------------------------------------------
[DOUBLEPOST=1436844668][/DOUBLEPOST]FindPlayerByName(name)
Example usage:Code:function PLUGIN:FindPlayerByName( playerName ) -- Check if a player name was supplied. if not playerName then return end -- Set the player name to lowercase to be able to search case insensitive. playerName = string.lower( playerName ) -- Setup some variables to save the matching BasePlayers with that partial -- name. local matches = {} local itPlayerList = global.BasePlayer.activePlayerList:GetEnumerator() -- Iterate through the online player list and check for a match. while itPlayerList:MoveNext() do -- Get the player his/her display name and set it to lowercase. local displayName = string.lower( itPlayerList.Current.displayName ) -- Look for a match. if string.find( displayName, playerName, 1, true ) then -- Match found, add the player to the list. table.insert( matches, itPlayerList.Current ) end if string.len( playerName ) == 17 then if string.find( rust.UserIDFromPlayer( itPlayerList.Current ), playerName ) then -- Match found, add the player to the list. table.insert( matches, itPlayerList.Current ) end end end -- Return all the matching players. return matches end
Credits: MughisiCode:local targetPlayer = self:FindPlayerByName( namestring ) Item = global.ItemManager.CreateByName("stones", "1000"); Item.isBlueprint = false; local Inventory = targetPlayer.inventory; Inventory:GiveItem(Item, nil);
---------------------------------------------------------------------------
[DOUBLEPOST=1436844912][/DOUBLEPOST]SetHostname(hostname)
Usage:Code:function PLUGIN:SetHostname(hostname) rust.RunServerCommand("server.hostname", hostname) rust.RunServerCommand("server.writecfg") end
---------------------------------------------------------------------------Code:SetHostname(hostname)
[DOUBLEPOST=1436845117][/DOUBLEPOST]Print(self, message)
This will make printing dynamic in that it you will only have to change self.Title and the Print function will always display that.Code:local function Print(self, message) print("[" .. self.Title .. "] " .. message) end
Example Usage:
Code:Print(self, "You need to set the hostname by using /" .. self.Config.Command .. " <newhostname>")
Useful Functions [LUA]
Discussion in 'Rust Development' started by Norn, Jul 14, 2015.
-
Add multiple commands from a config value or hard coded values. This just reduces having multiple lines calling the same thing.
Default config loading.Code:for _, cmd in pairs({'cmd1','cmd2'}) do command.AddChatCommand(cmd, self.Plugin, "cmdFunction") end
Check user for a permission, if they are a mod or higher they have access.Code:function PLUGIN:LoadDefaultConfig() -- Settings self.Config.Settings = self.Config.Settings or {} self.Config.Settings.Setting1 = self.Config.Settings.Setting1 or "true" self.Config.Settings.Setting2 = self.Config.Settings.Setting2 or 5 -- Messages self.Config.Messages = self.Config.Messages or {} self.Config.Messages.Message1 = self.Config.Messages.Message1 or "Message One" self.Config.Messages.Message2 = self.Config.Messages.Message2 or "Message Two" self:SaveConfig() end
Code:local function HasPermission(player, perm) local userId = rust.UserIDFromPlayer(player) if player:GetComponent("BaseNetworkable").net.connection.authLevel > 0 then return true end if permission.UserHasPermission(userId, perm) then return true end return false end -
Split chat messages into multiple messages after set amount of character limit. Its intelligent and doesnt cut words. Returns a table with all messages.
Converts a ConsoleSystem.Arg used in chat and console commands to a lua table.Code:local function SplitLongMessages(msg, charlimit) local length = msg:len() local msgTbl = {} if length > 128 then msg = msg:sub(1, 128) end if length > charlimit then while length > charlimit do local subStr = msg:sub(1, charlimit) local first, last = subStr:reverse():find(" ") if first then subStr = subStr:sub(1, -first) end table.insert(msgTbl, subStr) msg = msg:sub(subStr:len() + 1) length = msg:len() end table.insert(msgTbl, msg) else table.insert(msgTbl, msg) end return msgTbl end
Usage:Code:local function ArgsToTable(args, src) local argsTbl = {} if src == "chat" then local length = args.Length for i = 0, length - 1, 1 do argsTbl[i + 1] = args[i] end return argsTbl end if src == "console" then local i = 1 while args:HasArgs(i) do argsTbl[i] = args:GetString(i - 1) i = i + 1 end return argsTbl end return argsTbl end
Calculate hours, minutes and seconds until specific timestamp and return as formatted string.Code:-- chat command function PLUGIN:cmdTest(player, cmd, args) local args = ArgsToTable(args, "chat") local 1st_arg = args[1] local 2nd_arg = args[2] ... end -- console command function PLUGIN:ccmdTest(arg) local args = ArgsToTable(arg, "console") local 1st_arg = args[1] local 2nd_arg = args[2] ... end
Code:local function TimeUntilTimestamp(timestamp) local now = time.GetUnixTimestamp() local time = timestamp - now local hours = tostring(math.floor(time / 3600)):format("%02.f") local minutes = tostring(math.floor(time / 60 - (hours * 60))):format("%02.f") local seconds = tostring(math.floor(time - (hours * 3600) - (minutes * 60))):format("%02.f") return tostring(hours.."h "..minutes.."m "..seconds.."s") end
