Player/SendLua

From Garry's Mod
(Difference between revisions)
Jump to: navigation, search
(Note)
(Example 2)
Line 15: Line 15:
 
|Code=local pl = Entity( 1 )
 
|Code=local pl = Entity( 1 )
 
pl:SendLua( "print( 'Hello World' )" )
 
pl:SendLua( "print( 'Hello World' )" )
 +
}}
 +
{{Example
 +
|Description=Replacement of SendLua with {{Lib|net}}.
 +
This example replaces <pre class="inline">ply:SendLua("chat.AddText(\"Done\")")</pre>, <pre class="inline">ply:SendLua("chat.AddText(\"Error! Wrong arguments\")")</pre> and <pre class="inline">ply:SendLua("chat.AddText(\"An error occurred during runtime\")")</pre>
 +
|Code=-- 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)
 +
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)
 
}}
 
}}

Revision as of 11:49, 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)
	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