当前位置:网站首页>Roblox sword nine sword two
Roblox sword nine sword two
2022-06-29 07:42:00 【Xiao Yang who loves coding】
Roblox Sword two of sword nine 【 Sword of imperial code 】
Royal code navigation
- Roblox Sword two of sword nine 【 Sword of imperial code 】
- Preface
- One 、 Learning route
- Two 、Lua Basics
- Two 、Lua Table of (table)
- 3、 ... and 、 Meta table Introduction
- Four 、UGC Platform and Lua The combination of development
- 5、 ... and 、 Conclusion
Preface
Blogger Yu 2020 Year into the pit UGC Game development , So far, a number of UGC works , Such as power crisis 、 The scourge of the heroic expedition 、 Reign of Swords 、 Versatile millionaire …… so to speak UGC Game development is a new outlet for entrepreneurship . Just like today's low code , Easy to use , More production , Quick results .
This blog mainly takes you to break through LUA This scripting language - With Roblox For example .
One 、 Learning route
- Picture form

Two 、Lua Basics
As far as we know UGC Game creation platform 【 Restart the world -Reworld】、【Roblox】 Both use Lua This scripting language UGC Game Programming . Bloggers' first object-oriented language is C#, Mainly for GIS Development service . Later I met UGC Game development , Learned auxiliary language -Lua,Lua This scripting language may be unheard of by many people , But this powerful Glue language It's really around us , Take games for example
- It's all right with C/C++、C#、Java Interact perfectly
- Definition 、 Store and manage basic game data
- Create and maintain a developer friendly game storage and loading system
- Create functional prototypes , It can be ported with high-performance language later
- Playing games
Hot updateoperation 【 namelyPatch, Commonly used 】
1、Lua Introduce
Lua It's a kind of
Lightweight and compactOfScripting language, It consists of standardC LanguageWrite and beOpen source, It can be very convenientAnd other proceduresConductIntegrateandExpand(C#,Java…), It is designed toEmbedded applicationsin , Flexible extension and customization for applications .
1.1 Explanatory language
Lua It's script language , Scripting language yes Explanatory language One of them . Classification for programming languages , There are different types of classification from different angles . among Compiler language and Explanatory language Mainly with How to execute the program And classification . For specific differences between the two, please refer to Poke me
Simply speaking
- Interpretive language is
The interpreter executes while interpretingProgram ,NoGenerateExecutable file. - Compiled languages are
The compiler compiles before executingProgram , GenerateExecutable file, canrepeatfunctionExecutable file.
2、Lua characteristic
- Support process oriented programming and
Functional programming Automatic memory management, Only one generic type ofsurface (table), But it can be doneArray,Hashtable,aggregate,object.- Language built-in matching pattern .
- Closure (closure).
- A function can also be regarded as a value .
- Provide
Multithreading(coroutines, Not a thread supported by the operating system ). - adopt
ClosureandtableCan easily supportobject-orientedSome of the key mechanisms needed for editing , such asData abstraction,Virtual functions,Inheritandheavy loadetc. .
3、Lua Data type of
3.1 data type
Lua There are eight main data types in , Namely nil、boolean、number、string、function( Functional programming )、table、thread、userdata.
| data type | describe |
|---|---|
| nil | This is the easiest one , Only value nil Belong to this class , It means a Invalid value ( stay Conditional expression Equivalent to false). |
| boolean | Contains two values :false and true. |
| number | Express Double precision type real floating point number |
| string | The string consists of A pair of double or single quotation marks To express |
| function | from C or Lua Functions written |
| userdata | Represents any... Stored in a variable C data structure |
| thread | Represents an independent line of execution , be used for Execute the collaboration program |
| table | Lua In the table (table) It's actually a " Associative array "(associative arrays), Array Of Indexes It can be Numbers 、 character string or Table type . stay Lua in ,table Is created by " Construct expression " To complete , The simplest construction expression is {}, To create an empty table . |
Example
print(type("Hello world")) --> string
print(type(10.4*3)) --> number
print(type(print)) --> function
print(type(type)) --> function
print(type(true)) --> boolean
print(type(nil)) --> nil
print(type(type(X))) --> string
3.2 Lua Variable
3.2.1 Variable type
Lua The variables are 3 Types
- Global variables
- local variable (local)
- Fields in table
3.2.2 Variable Convention
- Lua All in
Variables are all global variables, Even if it isIt is also a global variable in the function body,Unlessuselocal keywordExplicitly declared aslocal variable,local variableThe scope of isFrom the declaration to the end of the statement block. In short ,If not local Declarative , It's all global variables.【a key】 - Variables before use ,
A statement must be made - Variable
The default value is zero nil - Lua It can be applied to multiple variables
simultaneous assignment,Variable listandList of valuesNeed to usecommaseparate - Lua Language support
Direct assignmentandThere is no need to declare a data typeThe operation of .
Example
val = 10 -- Global variables
local locVal = 10 -- local variable
function value1()
c = 20
local d = 10
end
value1()
print(val, locVal, c, d) -- After executing the function The value of a local variable cannot be printed , Global variables can
do
local val = 4 -- Defining local variables val
locVal = 5 -- Reassign a local variable
print(val, locVal) -- Print do Internal val = 4 as well as locVal = 5
end
print(val, locVal) -- there val Global variable val,locVal For the local variable to be re assigned locVal
-- Multiple variables are assigned at the same time
a, b = 10, 2*x -- a=10; b=2*x
- Add Note writing
-- Single-line comments
perhaps
--[[ Multiline comment --]]
4、 Control statement
4.1 Branch statement
if( Boolean expression ) then
--[ The Boolean expression is true When the statement block is executed --]
else
--[ The Boolean expression is false When the statement block is executed --]
end
4.2 Loop statement
| Type of cycle | describe |
|---|---|
| while | The cycle is Condition is true when , Let the program Repeat Some statements . Before executing the statement, check whether the condition is true. |
| for | loop Repeat the specified statement , repeat frequency Can be found in for In the sentence control . |
| repeat…until | Repeat the loop , until designated Conditions by really When is stop |
4.2.1 while loop
while(condition)do
< Executor >
end
4.2.2 for loop
1) The number for loop
for var=exp1,exp2,exp3 do
< Executor >
end
varfromexp1Change toexp2, Every time you change itexp3 Step lengthIncreasing var, andDo it once ” Executor”.- exp3 It's optional , If you don't specify ,
The default is 1.
2) Generic for loop
notes Game development Commonly used
Generic for The loop iterates through all the values through an iterator function , similar java Medium foreach sentence .
-- Print array a All values
for k,v in ipairs(a) do
print(v)
end
Briefly ,k,v by Key value pair ,k yes Index value ,v yes The element value corresponding to the index .
4.2.3 repeat…until loop
Do it first , Then judge the conditions
repeat
< Executor >
while(condition)
Loop control statement
- break Exit the current loop or statement , The script starts to execute
The following statement.
lua There is nocontinue key word - In disguise
continue
for i = 1, 100 do
while true do
if i % 2 == 1 then break end
-- There's a lot of code here
--
--
break
end
end
4.3 function
optional_ overall situation / Local function Function name (argument1, argument2, argument3..., argumentn)
The body of the function
return Function return value
end
- Lua A function can
Return multiple result values, stay return After listing the list of values to be returned, you can return multiple values , Such as return m, mi - Lua The function can accept
Variable parameters, and C The language is similar to that used in function parameter listsThree points (…)Indicates that a function has variable arguments ,Lua Put the parameters of the function in a place calledargIn the table of ,#argIt means incomingParametersOfNumber
Two 、Lua Table of (table)
1、table Introduction to
surface (Table)yes Lua In languageMost importantly( In fact, it isonlyOf ) And powerfuldata structure.
Use table ,Lua Language can be expressed in a simple 、 Express in a unified and efficient wayArray、aggregate、RecordandMany other data structures.
Lua Language is also usedsurfaceTo expresspackage ( package )andOther objects.
Lua The table in language is essentially an auxiliary array ( associative array ), This kind of array can not only useThe numberAs index , You can also usecharacter stringorAny other type of valueAsIndexes(nil With the exception of).
Values stored in the same table can have different type indexes , And you can pressDemand grows to accommodate new elements
Example
When a function is called math.sin when , We might think so “ Called math Functions in the library sin”;
And for Lua language , Its actual meaning is “ In string "sin" Search the table for the key math”.
2、table Use
2.1 initialization
1、
local a = {
}
2、
local a = {
["x"] = 12,["mutou"] = 99,[3] = "hello"}
print(a["x"])
3、
local a = {
x=12,mutou=99,[3]="hello"}
print(a["x"])
4、
local a = {
x=12,mutou=99,[3]="hello"}
print(a.x)
notes :
1 Initialize for empty table ,2 General operations for initializing and assigning initial values ( Use [] For index , Use = Associate an index with a value )
3 and 4 Indexing is a concise way of writing strings
Default numeric index ( List constructor )
local a ={
[1]=12,[2]=43,[3]=45,[4]=90}
Concise Edition local a = {
12,43,45,90}
print(a[1])
- Use
List constructorwhen ,The default index is from 1 Start(instead of 0), And so on . This is different from other languages . No,giveIndexesOf , fromTable AutogiveDigital index
2.2 operation
2.2.1 Access elements
a key
Use . This grammar is followed by String index value or [ Index value ] Can access table The index of corresponds to Element value
notes :table For the length of the # Table name To said
local a = {
{
x = 1,y=2},
{
x = 3,y = 10}
}
print(a[1].x)
print(#a)
Add in pairs and in ipairs The difference between
in pairs The method is more general , Don't overemphasize table Medium key value
in iparis The method emphasizes table Of key The values are in order , When the sequence is interrupted ,for Cycle termination
2.2.2 Insert
Use table.insert() Method
tab2 = {
"a",2,"b",5} -- Define a table
table.insert(tab2,2,"king") -- Specifies that a value is inserted at a certain location
for i, v in ipairs(tab2) do
-- print(v) -- Output a king 2 b 5
end
table.insert(tab2,3) -- If there is no designated location , By default, the value is inserted at the end position
for i, v in ipairs(tab2) do
-- print(v) -- Output a king 2 b 5 3
end
tab3 = {
"d",7,"e"}
table.insert(tab2,tab3) -- take table Insert table
for i, v in ipairs(tab2[7]) do
--print(v) -- Output d 7 e
end
tab2["mm"]="mmm" -- Add a new key value pair Below for Iterator selection pairs To traverse the new key value pair , Instead of ipairs
for i, v in pairs(tab2) do
print(i,v) -- Output 1 a ; 2 king ; 3 2 ; 4 b ; 5 5 ; 6 3 ; 7 table ;mm mmm
end
2.2.3 Delete
Use table.remove() Method
tab4 = {
1,4,"tt","jj"}
table.remove(tab4,1) -- Removes the from the specified location table value , If no location is specified , The last element is removed by default
for i, v in ipairs(tab4) do
print(v) -- Output 4 tt jj
end
2.2.4 to update
visit The element corresponding to the index and assignment that will do
2.2.5 Sort
Use table.sort() Method
language = {
"lua","java","c#","c++"}
table.sort(language) -- Only table One parameter , Use lua The default sort method is sort
for i, v in ipairs(language) do
-- print(v) -- Output c# c++ java lua
end
local function my_comp1(element1,element2) -- Custom comparison function As table.sort() Parameters
return element1<element2
end
table.sort(language,my_comp1)
for i, v in ipairs(language) do
print(v) -- Output c# c++ java lua
end
local function my_comp2(element1,element2) -- Custom comparison function As table.sort() Parameters
return element1>element2
end
table.sort(language,my_comp2)
for i, v in ipairs(language) do
-- print(v) -- Output lua java c++ c#
end
local function my_comp3(element1,element2) -- Custom comparison function As table.sort() Parameters
if element1==nil then
return false
end
if element2==nil then
return true
end
return element1>element2
end
language[2]=nil --table There is nil Existing situation
table.sort(language,my_comp3)
for i, v in ipairs(language) do
-- print(v) -- Output lua c++ c#
end
2.2.6 Remove the contents of the entire table
- Multiple table names can be referenced to the same table , When the last reference is released , The garbage collector will eventually delete the table .
- Set the table to
nil, Then wait for garbage collection or enforce a garbage collection (collectgarbage). - in other words , In program development , Need to put
The table is emptyCome onFree table resources. - If
Do not want to empty, You can tryweak tableUse , Need to useTuplesThe concept of
local table = {
1,1,1,1,1,1,11,1,1}
--1. This method is more violent , Direct will table empty
table = {
} perhaps table=nil -- Release table References to
print(#table) --- nil
--2. Remove the entire by traversing the loop table Elements in
for i = #table ,table do
table.remove(table,i)
i = i - 1
end
-- Be careful : Removing table When the elements in ,table The elements in the will be filled automatically , So remove all from the last bit
3、 ... and 、 Meta table Introduction
1、 Meta table Introduction
Lua Of
surfaceThe essence is actually asimilar HashMapThings that are , There are many elementsKey-Value Yes, If you try tovisitIn a tableElements that do not existwhen , It will trigger Lua A set ofSearch mechanism, This mechanism is also used to simulate similar “Inherit” act
A meta table is like a“ Operation guide ”, It contains a series ofOperational solutions, for example__index MethodIt defines thissurfacestayIndex failedWhat to do in case of .
The method to set the meta table issetmetatable(son, father) -- hold son Of metatable( Metatable ) Set to father
The key word issetmetatable
1.1 Lua Rules for finding elements in a table
- Find in table , If you find , Return the element , If you can't find it, continue
- . Judge whether the table has meta table , If there is no meta table , return nil, If there is a meta table, continue
- Judge whether the meta table has
__indexMethod , If __index Method is nil, Then return to nil; If __index The method is asurface, berepeat 1、2、3; If __index The method is afunction, Then return toThe return value of this function
2、 object-oriented
Three characteristics of object-oriented
- encapsulation
- Inherit
- polymorphic
Detailed introduction can be moved step by step Java The sword opens the gate of heaven ( Two )
Lua Object oriented is not supported , But it can be used Metatable Realization object-oriented
2.1 Official practice
- Class definition
- The method is generally : This grammar sugar means
- self Refer to oneself
local Class= {
value=0 } -- Defining attributes
function Class:new(o) -- Definition new Method , The template can be modified
o=o or {
};
setmetatable(o,self); -- take self Set to o The yuan table of
self.__index=self; -- Point to your
return o;
end
function Class:showmsg() -- Define methods
print(self.value);
end
local test = Class:new(); -- Class instantiation
test:showmsg(); -- Method call
- Class inheritance
local A = Class:new(); -- class A Definition
function A:new(o) -- new Method , The template may not be modified
local o = o or {
};
setmetatable(o,self);
self.__index=self;
return o;
end
function A:showmsg( ) -- Common method
print (self.value); -- Properties of the parent class
print("zhishi Test ah ah ")
end
local s = A:new({
value=100}); -- class A initialization
s:showmsg(); -- Method call
2.2 Elegant way
class.lua file
--[[ Simulate the base class of inheritance structure ]]
local _class = {
}
function Class(super)
local class_type = {
}
class_type.ctor = false -- Constructors
class_type.super = super -- Inherit
class_type.New = function(...) -- example
local obj = {
}
do
local create -- Create closure functions
create = function(c, ...)
if c.super then -- There is a parent class , Recursive create
create(c.super, ...)
end
if c.ctor then
c.ctor(obj, ...) -- Constructors
end
end
create(class_type, ...) -- Closure function entry
end
setmetatable(obj, {
__index = _class[class_type]}) -- Look up meta table
return obj
end
local vtbl = {
} -- A temporary table
_class[class_type] = vtbl -- Member variable assignment
setmetatable( -- assignment 、 Look up meta table (vtbl Find and assign )
class_type,
{
__newindex = function(t, k, v)
vtbl[k] = v
end,
--For call parent method
__index = vtbl
}
)
if super then -- Inheritance lookup meta table (vtbl assignment , Returns the parent class value )
setmetatable(
vtbl,
{
__index = function(t, k)
local ret = _class[super][k]
vtbl[k] = ret
return ret
end
}
)
end
return class_type
end
-------- Use
-- Of course, call class.lua file
base=Class() -- Define a base class base_type
function base:ctor(x) -- Definition base_type Constructor for
print("base ctor")
self.x=x
end
function base:print_x() -- Define a member function base:print_x
print(self.x)
end
function base:hello() -- Define another member function base:hello
print("hello base")
end
-- Subclass implementation
child=Class(base);
function child:ctor()
print("child ctor");
end
function child:hello()
print("hello child")
end
-- call
local a=child.New(21);
a:print_x();
a:hello();
Both methods have advantages and disadvantages
Bloggers use
The second kindThe way , The second method is not different from object-oriented programming .local Variable is to create a new variable , Obey the rule that the child scope overrides the parent scope .
Especially for require "modname" Module in , At the time of writing , You cannot use global variables directly , Because the same variable will save its variable state and affect other uses . The best way to deal with it is to rely on the input as much as possible , Function internal definition local Variables, etc .
local Faster access ( as a result of local Variables are stored in lua Inside the stack of is array operation , The global variables are stored in _G Medium table in , Less efficient than the stack )
Encapsulation is possible , but
Inconvenient to embedIn this code , So we ignoreencapsulationOfDeep meaning, stay Lua in , Encapsulation is simply understood asattributeandMethodPut it all together .
Four 、UGC Platform and Lua The combination of development
1、 Client script
The client program is written in the client script , The main functions of the program are
Submit data, Players will use the device toInput, Like clicking on a button 、 Click the mouse, etc ,Client programGet the player'sinput dataAfter simple treatmentSubmit to server.Client scriptThe only parts created areLocal playersonlyCan seeOf .
- With Roblox For example ,
LocalScriptIs used when connecting to Roblox On the client side of the server Lua Code Lua Source container .
2、 Server scripts
The server code is written in the server script , The main functions of the program are
Analyze and process these data, And then putThe processing result is returned to the client for display.Server scriptsThe part created isAll playersallCan seeOf .
image UGC Every game developed in the game development platform , The platform will allocate corresponding
Server capacity.
- With Roblox For example ,
Script( Script ) It's a kind of Lua Code container , Its contents can be run on the server .
- Server scripts and client-side scripts can be accessed through
RemoteEvent、Event objectAnd other different communication mechanisms on different platformssignal communication
3、 Modular development
In the development of large projects , We adopt a divide and conquer strategy , Divide large projects into small modules , Interfaces are reserved between small modules , After integration, the project will be formed .
stay UGC Platform development games , Modularity is mainly reflected in the following two aspects
- Use
Object oriented programming ideaCarry out engineering development - Use
General moduleOne by oneModule writing, forClient or serverScript call 【 The key word isrequire, Common module scriptsallCan be called by client and server scripts 】
With Roblox For example , Sure ModuleScript this Lua Source container , It only runs once , And must return the same value .
And then in ModuleScript As a unique parameter , By calling require Return this value .
In the opinion of bloggers , The module can be divided into client and server modules
Client module
- routine UI Input 【 Send a request 】
- Local scene configuration
- The local store
- Local logic
Server scripts
- General tools
- Server storage
- Controller forward 【 Receiving request 】
- Service Business logic
- Mapper Data persistence
5、 ... and 、 Conclusion
////////////////////////////////////////////////////////////////////
// _ooOoo_ //
// o8888888o //
// 88" . "88 //
// (| ^_^ |) //
// O\ = /O //
// ____/`---'\____ //
// .' \\| |// `. //
// / \\||| : |||// \ //
// / _||||| -:- |||||- \ //
// | | \\\ - /// | | //
// | \_| ''\---/'' | | //
// \ .-\__ `-` ___/-. / //
// ___`. .' /--.--\ `. . ___ //
// ."" '< `.___\_<|>_/___.' >'"". //
// | | : `- \`.;`\ _ /`;.`/ - ` : | | //
// \ \ `-. \_ __\ /__ _/ .-` / / //
// ========`-.____`-.___\_____/___.-`____.-'======== //
// `=---=' //
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //
// The Buddha bless Never goes down never BUG //
////////////////////////////////////////////////////////////////////
边栏推荐
- Viewing application and installation of Hana database license
- 部署Prometheus-server服务 system管理
- 1032 Sharing
- IMX6DL4.1.15支持EIM总线(下)——配置原理分析。
- How to select CRM brand suppliers in garment industry?
- cv::Mat与Base64转换(含图片压缩解压等流程)
- How to solve the cross domain problem of mobile phone accessing the web in the web development scenario
- KingbaseES 中select distinct on 语句
- 循环嵌套问题:为什么大循环在内,小循环在外可以提高程序的运行效率
- Schnuka: what is visual positioning system? How visual positioning system works
猜你喜欢

部署Prometheus-server服务 system管理

施努卡:3d机器视觉检测系统 3d视觉检测应用行业

九州云助力内蒙古“东数西算”工程,驱动测绘行业智慧新生态

Explain canfd message and format in AUTOSAR arxml in detail

编译原理王者之路

100 lectures on Excel advanced drawing skills (VI) - practical application cases of Gantt chart in project progress

1032 Sharing

Schnuka: what is visual positioning system? How visual positioning system works

Listen to textarea input through Keyup to change button style
如何看待软件测试培训?你需要培训吗?
随机推荐
How to solve the cross domain problem of mobile phone accessing the web in the web development scenario
Matlab Simulink simulation and analysis of power grid sweep frequency
国家安全局和CISA Kubernetes加固指南--1.1版的新内容
Schnuka: what is visual positioning system? How visual positioning system works
Markdown skill tree (8): code blocks
KingbaseES应对表年龄增长过快导致事务回卷
Concurrent idempotent anti shake
并发幂等性防抖
cv2.cvtColor
Deploy Prometheus server service system management
道闸控制器通讯协议
【工控老马】单片机与西门子S7-200通信原理详解
TREE ALV 展开Node或者点击Toolbar按钮时DUMP(CL_ALV_TREE_BASE==============CP|SET_ITEMS_FOR_COLUMN)
Markdown skill tree (5): picture
Markdown skill tree (6): List
358. K 距离间隔重排字符串 排序
Schnuka: 3D visual recognition system 3D visual inspection principle
服装行业的CRM品牌供应商如何选型?
Fluent imitates uiswitch
719. 找出第 K 小的数对距离(二分)