Player/SendLua

From Garry's Mod
(Difference between revisions)
Jump to: navigation, search
(Example 2)
m (note)
Line 33: Line 33:
 
net.Receive("MsgForMyAddon",function()
 
net.Receive("MsgForMyAddon",function()
 
local id,text = net.ReadUInt(2)
 
local id,text = net.ReadUInt(2)
 +
-- Note: I use if + elseif because I have only 3 different ids, if you have more than 5 consider using a table lookup (table-set)
 
if id == MSG_DONE then
 
if id == MSG_DONE then
 
text = "Done"
 
text = "Done"

Revision as of 14:18, 14 January 2020

 Player:SendLua( )

Contents

Description

Executes a simple Lua string on the player.

NOTE

The string is limited to 254 bytes. Instead of sending Lua code with this function, consider using the net library for more advanced server-client interaction, see example 2 for SendLua replacement

Arguments

string script

The script to execute.

Examples

Example

Sends "Hello World" to the client's console.

local pl = Entity( 1 )
pl:SendLua( "print( 'Hello World' )" )


Examples

Example

Replacement of SendLua with net library.

This example replaces
ply:SendLua("chat.AddText(\"Done\")")
,
ply:SendLua("chat.AddText(\"Error! Wrong arguments\")")
and
ply:SendLua("chat.AddText(\"An error occurred during runtime\")")
-- SERVER
local MSG_DONE,MSG_ERROR_ARGUMENTS,MSG_ERROR_RUNTIME = 0,1,2
util.AddNetworkString("MsgForMyAddon")

function SendMsg(ply,id)
	net.Start("MsgForMyAddon")
	net.WriteUInt(id,2) -- If you want to calculate required bits amount use ceil(log(amountOfMsgIncludingZero) / log(2))
	net.Send(ply)
end

-- CLIENT
local MSG_DONE,MSG_ERROR_ARGUMENTS,MSG_ERROR_RUNTIME = 0,1,2
net.Receive("MsgForMyAddon",function()
	local id,text = net.ReadUInt(2)
	-- Note: I use if + elseif because I have only 3 different ids, if you have more than 5 consider using a table lookup (table-set)
	if id == MSG_DONE then
		text = "Done"
	elseif id == MSG_ERROR_ARGUMENTS then
		text = "Error! Wrong arguments"
	elseif id == MSG_ERROR_RUNTIME then
		text = "An error occurred during runtime"
	end

	chat.AddText(text)
end)


Personal tools
Navigation