autocad lua extension - qs...

67
QS Informatica AutoCAD LUA Extension Rel. 1.00 - November 2002 The official guide to the AutoCAD/TOP customization using the LUA language.

Upload: dodung

Post on 24-Mar-2018

247 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

QS Informatica

AutoCAD LUA ExtensionRel. 1.00 - November 2002

The official guide to the AutoCAD/TOP customization using the LUA language.

Page 2: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Introduction

Why LUA? ...

Page 3: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Global functions

Syntax:command(command, arg1, arg2, ...)

Description:Runs an AutoCAD Command. Syntax is very similar to the counterpart AutoLisp function.

Examples:command({'_ERASE', entlast(), ''})

Deletes the last inserted entity

local newname = "mydrawing.dwg"command({"_SAVEAS", "", newname})

Saves the current drawing with a new name

Syntax:dwgopen(dwgfilename)

Description:Opens a new drawing. Dwgfilename is the pathname of the dwg to open.

Examples:local options={

filter = 'All files/*.*/Files AutoCAD/*.dwg///',nome = "",title = "Select your favourite file"

}

local fname = GetFileNameIn(options)if fname and FileExists(fname) thendwgopen(fname)end

This example shows how to select and load a dwg file into AutoCAD

Syntax:menucmd(str)

Description:Same as AutoLisp

Examples:

Syntax:

Page 4: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

foreach_block(pattern-name, foo(block))

Description:Looks for inserted blocks with name matching “pattern-name” end applies on them the function“foo” passing the “block” as parameter. Research belongs to the current space (model/paper)

Examples:foreach_block(“TAB-*”, function(e)print(“Block found: \n”)

end)

This function prints the message for every block matching the “TAB-*” pattern.

Syntax:wcmatch(str, pattern)

Description:Executes a pattern matching between “srt” and “pattern”. Pattern can contain:

* = every char[abc] = from 'a to 'c'

Examples:wcmatch('prov123', 'prov*')

Return 1

Page 5: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Variables

Syntax:getvar(VarName)

Description:Returns the current value of the passed AutoCAD variable. To obtain the AutoCAD variables listplease refer to the current AutoCAD documentation.

Examples:local cmdecho = getvar(“CMDECHO”)

Return the value of “CMDECHO”

Syntax:setvar(nomeVar, valoreVar)

Description:Sets the value of “VarName” with “VarValue”.

Examples:setvar(“CMDECHO”, 0)

Sets the current value of CMDECHO to OFF.

Syntax:DbModPush()

Description:Saves the value of the DBMOD variable into an internal buffer. Has to be used with the“DbModPop()” function.

Examples:

Syntax:DbModPop()

Description:Reset the previous value of DBMOD. Has to be called once for every “DbModPush” call.

Examples:

Page 6: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Points

Syntax:Point()Point(x, y [, z])

Description:Creates a new Point object. Coordinates parameters are optional (0 would be used).

Examples:local orig = Point(0,0)local pt = Point(270, 159)

Creates a couple of Points in 0,0,0 and 270,159,0 respectively.

Syntax:getpoint(Prompt, [ReferencePoint])

Description:The user can specify a point by pointing whithin the AutoCAD graphic area or by entering acoordinate in the current units format. If the “ReferencePoint” argument is present, AutoCADdraws a rubber-band line from that point to the current crosshairs position. “Prompt” is themessage.

Examples:local p1while not p1 do

p1 = getpoint(“Please select a point...”)end

Syntax:getcorner(ReferencePoint, [Prompt])

Description:The getcorner function takes a base point argument, based on the current UCS, and draws arectangle from that point as the user moves the crosshairs on the screen. “ReferencePoint” is theother corner. “Prompt” is optional

Examples:

Syntax:inters(p1, p2, p3, p4, Extend)

Description:All points are expressed in terms of the current UCS. If all four point arguments are 3D, inters

Page 7: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

checks for 3D intersection. If any of the points are 2D, inters projects the lines onto the currentconstruction plane and checks only for 2D intersection.

Examples:

Syntax:<Point>:getX()<Point>:getY()<Point>:getZ()

Description:The requested coordinate is returned by this function.

Examples:local pt1 = Point(125, 321)local pt2 = Point(562,36)local dx = abs(pt1:getX() - pt2:getX())

Returnes the delta X value.

Syntax:<Point>:setX(value)<Point>:setY(value)<Point>:setZ(value)

Description:These function set the requested coordinate at the passed value.

Examples:local ptins = Point() local ptbase = Point(123, 321)local width = 12local tolerance = 0.1ptins:setX(ptbase:getX() + (width + tolerance) * 0.5)

Syntax:<Point>:polar(Angle, Distance)

Description:Target another point from the current Point object. “Angle” is an angle expressed in radiansrelative to the world axis. Angles increase in the counterclockwise direction, independent of thecurrent construction plane. “Distance” is the distance from the specified “Point”

Examples:

local pt1 = getpoint("\nSelect first point ..:")

Page 8: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

local pt2 = pt1:polar(PI/2 , 12.45);

Syntax:<Point>:moveRel(dx, dy, dz)

Description:Target another point from the current Point object. “dx”, “dy”, “dz” are real values that will bealgebrically added to the current “Point”

Examples:

Syntax:<Point>:angle(Pt2)

Description:An angle, in radians will be returned. The angle is measured from the X axis of the currentconstruction plane, in radians, with angles increasing in the counterclockwise direction.Computation is intended to the line passing in “Point” and “Pt2”.

Examples:local pt1 = getpoint("\nSelect first point ..:")local pt2 = getpoint("\nSelect second point ..:")local pnt3 = pt1:polar(pnt1:angle(pnt2) , pnt1:distanceTo(pnt2)*2.0)

Syntax:<Point>:distanceTo(Pt2)

Description:The distance between “Point” and “Pt2” will be returned. If one or both of the supplied points is a2D point, then distance ignores the Z coordinates of any 3D points supplied and returns the 2Ddistance between the points as projected into the current construction plane.

Examples:

local pt1 = getpoint("\nSelect first point ..:")local pt2 = getpoint("\nSelect second point ..:")local dst = pt1:distanceTo(pt2)

Syntax:<Point>:equalTo(Pt2)

Description:Used to compare “Point” and “Pt2”. Must be used instead of the “=” operator. Return a truevalue if points are equals.

Examples:

Page 9: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Syntax:<punto>:asString()

Description:This method is suitable every time you require a string rappresesentation of your “Point” object.

Examples:

Page 10: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Entities

Syntax:entsel(Prompt) -> entity

Description:Every time you need to select an entity from the AutoCAD graphic sceen you would use thisfunction. “Prompt” is intended the prompt string to be displayed to users. If omitted, entselprompts with the message, "Select object”.

Return an “entity” object.

Examples:local ent= entsel("\nPlease select an AutoCAD entity:")if ent thenalert(“ent has been selected”)

elsealert(“selection failed”)end

This example ask you to select an AutoCAD entity and replies you a message.

Syntax:entlast() -> entity

Description:The entlast function is frequently used to obtain the name of a new entity that has just been addedwith the command function. To be selected, the entity need not be on the screen or on a thawedlayer.

Examples:local ent = entlast()ent:setColor(7)

This example turns the color of the last inserted entity to white.

Syntax:entmake(dxflist) -> entity

Description:A list of entity definition data is required. The “dxflist” argument must contain all of theinformation necessary to define the entity. If any required definition data is omitted, entmakereturns nil and the entity is rejected. If you omit optional definition data (such as the layer),entmake uses the default value.

Examples:

Page 11: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

local ent = entmake{ {0, “LINE”}, {10, Point(1,0,0)}, {11, Point(2,1,0)} }

This example creates a line entity from 1, 0 to 2, 1.

function DrawText(txt, pos, halign, valign, h, rot, stl)local ent = entmake{ {0, "TEXT"},

{10, Point(pos[1], pos[2])},--{11, Point(pos[1], pos[2])},{40, h},{7, stl},{72, halign},{73, valign},{50, d2r(rot)},{1, txt}}

return entend

This example creates a text entity

Syntax:tblobjname(tablename, symbolname) -> entity

Description:Returns the entity name of a specified symbol table entry. “tblname” is a string that identifies thesymbol table to be searched. The argument is not case sensitive.”symbolname” is a stringidentifying the symbol to be searched for.

Examples:

function GetBlockName(blk)local block = tblobjname("BLOCK", blk)local data = entget(BENT)local txt = data:assoc(2)return txtend

Syntax:<entity>:dxfName()

Description:Returns the entity type as string ("LINE", "CIRCLE", ...)

Examples:

Syntax:<entity>:entnext() -> <entity>

Page 12: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Description:Returns the name of the next object (entity) in the drawing. “nil” will be returned if the currententity is the last item into the AutoCAD database.

Examples:

function GetEntsFrom(entfrom)local ent = entfrom:entnext()local ss = selset.new()while ent do

ss:add(ent)ent = ent:entnext()

endreturn ssend

This function returns a selection set containing all the entities inserted after “entfrom”

Syntax:<entity>:textbox()

Description:Measures a specified text object, and returns the diagonal coordinates of a box that encloses thetext. This function is intended for text entities only.

Examples:

Syntax:<entity>:erase()

Description:The entity “entity” specified is deleted if it is currently in the drawing. The entdel function candelete both graphical and nongraphical entities.

Examples:

function sserase(ss)for i=0, ss:count() do

local ent = ss:item(i)if ent then ent:erase() end

endend

This example explains how to delete a selection set from the current AutoCAD drawing.

Syntax:<entity>:getColor()

Page 13: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Description:Returns the color of the current “entity”.

Examples:

function IsByLayer(ent)local color = ent:getColor()return (color == 256)

end

Syntax:<entity>:setColor(color)

Description:This function is a shortcut to set the color of the “Entity” object. “color” is intended as anumerical value into the AutoCAD color range.

Examples:

if ent thenent:setColor(256);ent:setLineType("BYLAYER");

end

This function turns the entity to bylayer values.

Syntax:<entity>:setLineType(linetypeName)

Description:This function is a shortcut to set the linetype of the “Entity” object. “linetypeName” is intended asas a string value into the AutoCAD valid linetypes.

Examples:

if ent thenent:setColor(256);ent:setLineType("BYLAYER");

end

This function turns the entity to bylayer values.

Syntax<entity>:getBlockAttributes()

Description:If the “entity” is an AutoCAD block, the function returns a LUA table with block's attributes. Intothe table the attribute name is the key and the attribute value is the value.

Page 14: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Examples:

function DumpAttributes()local block = entsel("\nSelect block...")if block then

local attributes = {}attributes = block:getBlockAttributes()alert(attributes)

endend

This function shows an alert box with the attributes of the selected block.

Syntax<entity>:entget() -> entlistentget(entity) -> entlist

Description:Return an “entlist” object. Retrieves an object's (entity's) definition data.

Examples:function PrintBlocksNames()-- select blocks inserted in the drawinglocal ss1 = selset.filter {{0 , "INSERT"}}if (ss1 and ss1:count() > 0) then

for i=0, ss1:count() dolocal ent = ss1:item(i)if ent thenlocal ed = entget(ent)local name = ed:assoc(2)-- print the name of the blockprint('\n' .. name)

endendss1:free()

endend

This function shows the name of every block inserted into the drawing.

Syntax:<entity>:setLayer(layerName)

Description:If you need to change the layer of the current “entity”. Provide a valid AutoCAD layer name andthe entity will be modified.

Page 15: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Examples:

Page 16: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Entities – Association Lists

Syntax:entmod(entlist)<entlist>:entmod()

Description:The entmod function updates database information for the entity name specified by the -1 group in“entlist”. Returns 1 if the function succeeds, nil if errors occur.

Examples:

function Freeze()local ed = tblsearch("LAYER", "MYLAYER")local status = ed:assoc(70)-- alert(status)status = bitor(status, 1)-- alert(status)ed:set(70, status)ed:entmod()

end

Syntax:tblnext(nometable, [rewind = 0]) -> entlist

Description:

Finds the next item in a symbol table. When tblnext is used repeatedly, it normally returns the nextentry in the specified table each time. The tblsearch function can set the next entry to be retrieved.If the rewind argument is present and is not nil, the symbol table is rewound and the first entry in itis retrieved.Set the “rewind” parameter to 1 the first time you call the function. You can omit the parameter infuture calls. Every time you call the function you gey the association list of the current element. Ifyou reach the end of the list a nil value will be returned.

Examples:

function ListDimensionsStyles()local dstylerepeatdstyle = tblnext('DIMSTYLE', not dstyle)if dstyle then print('\n' .. dstyle:assoc(2)) enduntil not dstyleend

Syntax:

Page 17: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

tblsearch(nometable, simbolname, [setnext = 0])

Description:Searches a symbol table for a symbol name. If tblsearch finds an entry for the given symbol name,it returns that entry in the format described for tblnext. If no entry is found, tblsearch returns nil.Every time the association list of the current element will be returned. Returns a “nil” value whenyou reach the last symbol.

Examples:

function InsertBlock(blk)if not tblsearch("BLOCK", blk) or blk ~= '_NONE' thenlocal blockpath = “C:\\myblocks\\” .. blk .. ".dwg"local pt = Point(0,0)command({"_-INSERT", block, pt, 0.0001, "", 0})endend

This example shows how to insert an external dwg as a block.

Syntax:<entlist>:count()

Description:Return the number of elements contained in “entlist”.

Examples:

Syntax:<entlist>:assoc(dxfcode)

Description:Return the dxf value associated to the provided dxfcode into the association list. Returns “nil” ifthe code doesn't exists.

Examples:

function PrintBlocksNames()-- select blocks inserted in the drawinglocal ss1 = selset.filter {{0 , "INSERT"}}if (ss1 and ss1:count() > 0) then

for i=0, ss1:count() dolocal ent = ss1:item(i)if ent thenlocal ed = entget(ent)local name = ed:assoc(2)-- print the name of the blockprint('\n' .. name)

end

Page 18: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

endss1:free()

endend

Syntax:<entlist>:nth(n)

Description:Returns the nth element of lst. If n is greater than the highest element number of lst, nth returns nil.

Examples:

Syntax<entlist>:set(dxfcode, value)

Description:Set the field associated at the “dxfcode” to the “value”. If the field “dxfcode” exists then it will bechanged, otherwise it will appended at the end of the list.

Examples:

local sset = selset.filter {{0 , "MTEXT"}, {8 , cella}}if (sset and sset:count() > 0) then

for i=0 to sset:count() dolocal ent = sset:item(i)if ent thenlocal entlst = ent:entget()entlst:set(1, “In a hole in the ground, there lived a hobbit...”)entlst:entmod()

endendsset:free()

end

This example replace every MTEXT text with the provided string.

Page 19: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Selection Sets

Syntax:selset.new()

Description:Create a new (empty) selection set. Since AutoCAD provide a limited number of selection setsplease remember to call the “selset:free()” function when the selection set is no longer used.

Examples:

function PrtGetEntities(prt, sets) prt:foreach(function(child)

local layer = child:getAttr("$lay")local ss = selset.filter {{8, layer}}if ss thentinsert(%sets, ss)

endend)

end

function AggregatePrt(prt1, prt2)local ssall = selset.new()prt2:foreach(function(prt)

local ss = PrtGetEntities(prt)if ss thenlocal len = ss:count()for i=0, len do%ssall:add(ss:item(i))

endss:free()

endend) prt1:aggr(ssall)ssall:free()

end

This function aggregates two parts.

Syntax:selset.usersel()

Description:Interactively creates a selecttion set, asking the user to select entities from the AutoCAD graphicscreen. Return a “selset” object.

Examples:

Page 20: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

function aggregate()local s = selset.usersel()if (s == nil) then return endlocal e = entsel("Select a part or press ENTER for the list")local prtif (e == nil) then

prt = top_prtselect()elseif (e ~= nil) then

prt = top_prtfroment(e)endif (prt == nil) then return endprt:aggr(s)top_updspotlight()

end

This function shows how to aggregate entities to one part.

Syntax:selset.filter( filterlist )

Description:This method works in the same way the AutoLisp function “ssget(“X”) does. You can provide yourown “filterlist”, this would change the returned “selset” object. Please refer to the “ssget filterlist” documentation provided with AutoCAD for more information.

An entity filter list is an association list that uses DXF group codes in the same format as a listreturned by entget. (See the DXF Reference for a list of group codes.) The “:filter” methodrecognizes all group codes except entity names (group -1), handles (group 5), and xdata codes(groups greater than 1000). If an invalid group code is used in a filter-list, it is ignored by ssget. TWhen a filter-list is provided, the function scans the selected objects and creates a selection setcontaining the names of all main entities matching the specified criteria. For example, you canobtain a selection set that includes all objects of a given type, on a given layer, or of a given color.

Examples:

local ss = selset.filter { {0, "POINT"}, {8, "0"} }

Creates a selection set with points lying on the “0” layer.

local ss1 = selset.filter {{62 , 2}}if (ss1 and ss1:count() > 0) then-- change the colorcommand("_CHPROP" , ss1 , "" , "_COLOR" , 1 , "" )-- free the selectionsetss1:free()

end

Changes entities color from 2 (Yellow) to 1 (Red)

Page 21: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

local sset = selset.filter {{0 , "MTEXT"}, {8 , “MYLAYER”}}if (sset and sset:count() > 0) thenalert('OK')sset:free()

end

Selects every MTEXT lying in “MYLAYER”

local ss = selset.filter {{0 , "LINE,CIRCLE"}}

This is a little trick, it works as a logical OR: your selection set would contains circles and lines.

Syntax:selset.ssget(options)

Description:This is the general “ssget” AutoLisp function replacement. It has been introduced for compatibilitybut you are expected to use this function exceptionally.The “options” parameter is a LUA table containing one or more parameters. Accepted parametersare:

Field name Type Description

mode string mode ('W' = Window, “C” = “Crossing, “F” = Fence, ...)

pt1 Point First point for window, crossing, ...

pt2 Point Second point for window, crossing, ...

filter list filter list (see “selset.filter”)

This function returns a “selset” object or nil.

Examples:

Syntax:<selset>:count()

DescriptionThis method returns the exact number of entities belonging to the “selset” selection set.

Examples:

function MovePrt(prt, from, to, activate) local prtcurif activate then

prtcur = top_pcur()prt:activate()

Page 22: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

endlocal ssall = selset.new()prt:foreach(function(prt)

local ss = PrtGetEntities(prt)if ss thenlocal len = ss:count()for i=0, len do%ssall:add(ss:item(i))

endss:free()

endend)if ssall and ssall:count() > 0 then

command({"_MOVE", ssall, "", from, to})endssall:free()if prtcur then

prtcur:activate()end

end

This example shows you how to emulate a Move Part command.

Syntax:<selset>:free()

Description:Since AutoCAD provides a limited number of selection set, it is very important to free them whenthey are no more functional.

Examples:

function PrtIsEmpty(prt)local layer = prt:getAttr("$lay")local ss = selset.filter {{8, layer}}local n = 0if ss then

n = ss:count()ss:free()

endreturn n == 0

end

Check whether the “part” passed to the function is empty or not.

Syntax:<selset>:item(index)

Page 23: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Description:Returns the object (entity) at the indexed element of the “selset” selection set. If index is negativeor greater than the highest numbered entity in the selection set, ssname returns nil.

Examples:

function SSJoin(ss1, ss2)if ss1 then

if ss2 and ss2:count() thenfor i=0, ss2:count() doss1:add(ss2:item(i))

endend

endreturn ss1end

This function joins two selection sets.

Page 24: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

User input

Syntax:initget(flags, keywords)

Description:Establishes keywords for use by the next user-input function call. The keywords are checked by thenext user-input function call when the user does not enter the expected type of input (for example, apoint to getpoint). If the user input matches a keyword from the list, the function returns thatkeyword as a string result. The application can test for the keywords and perform the actionassociated with each one. If the user input is not an expected type and does not match a keyword,AutoCAD asks the user to try again. The initget bit values and keywords apply only to the nextuser-input function call.Arguments:

bits

A bit-coded integer that allows or disallows certain types of user input. The bits can be addedtogether in any combination to form a value between 0 and 255. If no bits argument is supplied,zero (no conditions) is assumed. The bit values are as follows:

1 (bit 0) Prevents the user from responding to the request by entering only ENTER.2 (bit 1) Prevents the user from responding to the request by entering zero.4 (bit 2) Prevents the user from responding to the request by entering a negative value.8 (bit 3) Allows the user to enter a point outside the current drawing limits. This conditionapplies to the next user-input function even if the AutoCAD system variable LIMCHECK iscurrently set.16 (bit 4) (Not currently used.)32 (bit 5) Uses dashed lines when drawing a rubber-band line or box. For those functions withwhich the user can specify a point by selecting a location in the drawing area, this bit valuecauses the rubber-band line or box to be dashed instead of solid. (Some display drivers use adistinctive color instead of dashed lines.) If the system variable POPUPS is 0, AutoCAD ignoresthis bit.64 (bit 6) Prohibits input of a Z coordinate to the getdist function; lets an application ensurethat this function returns a 2D distance.128 (bit 7) Allows arbitrary input as if it is a keyword, first honoring any other control bits andlisted keywords. This bit takes precedence over bit 0; if bits 7 and 0 are set and the user pressesENTER, a null string is returned.

Note: Future versions of AutoLISP may use additional initget control bits, so avoid setting bits thatare not listed here.stringA string representing a series of keywords. The string argument is interpreted according to thefollowing rules:

Each keyword is separated from the following keyword by one or more spaces. For example,"Width Height Depth" defines three keywords.Each keyword can contain only letters, numbers, and hyphens (-).

There are two methods for abbreviating keywords:The required portion of the keyword is specified in uppercase characters, and the remainder ofthe keyword is specified in lowercase characters. The uppercase abbreviation can be anywherein the keyword (for example, "LType", "eXit", or "toP").The entire keyword is specified in uppercase characters, and it is followed immediately by acomma, which is followed by the required characters (for example, "LTYPE,LT"). The keywordcharacters in this case must include the first letter of the keyword, which means that "EXIT,X" isnot valid.

The two brief examples, "LType" and "LTYPE,LT", are equivalent: if the user types LT (in either

Page 25: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

uppercase or lowercase letters), this is sufficient to identify the keyword. The user can entercharacters that follow the required portion of the keyword, provided they don't conflict with thespecification. In the example, the user could also enter LTY or LTYP, but L would not be sufficient.If string shows the keyword entirely in uppercase or lowercase characters with no comma followedby a required part, AutoCAD recognizes the keyword only if the user enters all of it.

Examples:

initget(1)local pt = getpoint("\nSelect insertion point...")

Syntax:getstring(prompt)

Description:Pauses for user input of a string, and returns that string. Asks for a string as the AutoLisp/ADSfunctions do. Return the string or nil.

Examples:

Page 26: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Layers

Syntax:LayerGetInfo(layerName, [db])

Description:Returns nil if errors occur. Otherwise a table with layer info (color, linetype, ...) will be returned tothe user.

Examples:local info = LayerGetInfo(“0”)alert(info)

Syntax:LayerSetInfo(layerName, infos)

Description:Set the properties of the layer.

Examples:

local info = LayerGetInfo(“0”)LayerSetInfo(“MYLAYER”, info)

Copy the properties from layer “0” to layer “MYLAYER”

Syntax:LayerCreate(layerName[, infos] [,db])

Description:Creates a new layer. “infos” can be provided to initialize the new layer to default parameters.

Examples:

Page 27: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Strings

Syntax:strlen(str)

Description:Return the length (number of characters) of “str”.

Examples:

function findInStr(str, character)if str == "" then return nil endlocal lung = strlen(str)if lung>0 then

local count = 0while count < lung doif character == substr(str, count, 1) thenreturn count

endcount = count+1

endendreturn nil

end

This function return the index (0 based) of “character” in “str” or nil.

Syntax:substr(str, start, length)

Description:substr returns the portion of string specified by the “start” and “length” parameters.

Examples:

function IsInBOM(prt)local nome = prt:getName()if (not nome) or (nome == "") then nome = " " endif substr(nome, 0, 1) == "." then

return nilelse

return 1end

end

This examples returns 1 if the part blengs to the BOM, nil if the part has been excluded from theBOM (the name start with a dot) For example the name “.mypart will be automatically excludedfrom the BOM.

Syntax:

Page 28: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

strupr(str)

Description:Returns a string with all alphabetic characters converted to uppercase.

Examples:

local str = strupr(“abCdeF”)print (str) ---> “ABCDEF”

Syntax:strlwr(str)

Description:Returns a string with all alphabetic characters converted to lowercas.

Examples:

local str = strlwr(“abCdeF”)print (str) ---> “abcdef”

Syntax:strspn(str, delim)

Description:Returns de number of beginning characters of “str” defined in “delim”.

Examples:

local len = strspn('BBB223344', 'AB') -------> len value: 3 (number of 'B' at the beginning)

Syntax:trimLeft(str)

Description:This function returns a string with whitespace stripped from the beginning of “str”.

Examples:

local str = trimLeft(“ abcd”)print(str) ---> “abcd”

Syntax:trimRight(str)

Description:This function returns a string with whitespace stripped from the end of “str”.

Examples:

Page 29: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

local str = trimRight(“abcd ”)print(str) ---> “abcd”

Syntax:trim(str)

Description:This function returns a string with whitespace stripped from the beginning and end of “str”.

Examples:

local str = trim(“ abcd ”)print(str) ---> “abcd”

Syntax:strsubst(str, find, repl)

Description:strsubst replaces all occurrences of “find” in “str” by “repl”. This function is case sensitive.

Examples:

local str = strsubst( “I love my little cat”, 'cat', 'dog')print(str) ---> “I love my little dog”

Syntax:strSplitFixed(str, dim [, flags])

Description:This function is very useful every time you need to extract data from a text file composed by rowshaving several strings (with fixed length) attached in chain.Have a look at the parameters:

“str” is the row that need to be splitted“dim” is a LUA table with the dimension (in characters) of every column. A negative indexmeans that field will be discarded“flags” is a string containing several options that wold change the value returned:

“.rmulti” forces the function to return several values.“-trim” forces the function to trim every field in order to strip white spaces (before and after).

Examples:

Syntax:strSplitDelim(str, delim [, flags])

Description:

Page 30: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

This function is very useful every time you need to extract data from a text file composed by rowshaving several strings (separated by a delimiter) attached in chain.Have a look at the parameters:

“str” is the row that need to be splitted“dim” is a string containing the delimiter“flags” is a string containing several options that wold change the value returned:

“.rmulti” forces the function to return several values.“-trim” forces the function to trim every field in order to strip white spaces (before and after).

Examples:

Syntax:strSplitCdf(str)

Description:This function split the string “str”. This string is supposed to apply at the CDF (comma delimitedfile) standard. This standard requires that every value has to be separated by a comma.This function always returns a table.

Examples:

Syntax:strfill(length, strbase)

Description:Creates a new string with a given length “length”, joining several times the string “strbase”.

Examples:

strfill(5, 'ab') ---> ritorna "ababa"

Syntax:sprintf(fmt, ...)

Description:

Returns a string formatted by the usual printf conventions of the C library function sprintf. Seesprintf or printf on your system for an explanation of the general principles.

The standard LUA provide the function “format”.

type % Output Example

c Character a

d or i Signed decimal integer 392

Page 31: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

e Scientific notation (mantise/exponent) using e character 3.9265e2

E Scientific notation (mantise/exponent) using E character 3.9265E2

f Decimal floating point 392.65

g Use shorter %e or %f 392.65

G Use shorter %E or %f 392.65

o Signed octal 610

s String of characters sample

u Unsigned decimal integer 7235

x Unsigned hexadecimal integer 7fa

X Unsigned hexadecimal integer (capital letters) 7FA

p Address pointed by the argument B800:0000

n Nothing printed. The argument must be a pointer to integer wherethe number of characters written so far will be stored.

Examples:local test = sprintf("%02d", 2+2) ---> now test value is “04”

Page 32: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Regular Expressions

The object <regexp> represents a regular expression used in order to recognize patterns in strings.

Syntax:RegExp(str) -> <regex>

Description:Buids a regular expression object and returns the object itself.

Examples:

Syntax:<regex>:match(str [, pos])

Description:Try to perform a match of the regular expression on the provided string “str”, returning theposition of the first match.If “pos” is provided the fuction starts searching from the “pos” position”.

Examples:

Syntax:<regex>:matchall(str, pos) -> {s1, s2, ...}

Description:Perform the task on the complete string returning all blocks matching the provided regularexpression.If “pos” is provided the fuction starts searching from the “pos” position”.

Examples:

Page 33: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Lists Management

Syntax:lualist.keys(lst)

Description:Returns a list containing just the keys of the list “lst”.

Examples:

local tbl = {name = “Danny”,surname = “Square”}local tbl2 = lualist.keys(tbl)print(tbl2) ---> {'name', 'surname'}

Syntax:lualist.values(lst)

Description:Returns a list containing just the values of the list “lst”.

Examples:local tbl = {name = “Danny”,surname = “Square”}local tbl2 = lualist.values(tbl)print(tbl2) ---> {'Danny', 'Square'}

Syntax:lualist.join(list [, sep [, pre [, post]]])

Description:Sometimes you need creating a string which is the result of a concatenation task of several fields ofa table. Just provide the list and this function return the string. Some optional parameters areavailable.

<sep> this is the separator inserted between two fields. Default value is an empty space.<pre> if provided this string will be inserted as prefix of the returned string.<post> if provided this string will be appended at the end of the returned string.

Examples:

local tbl = {name = “Danny”,surname = “Square”,attributes = “is a genius”}

Page 34: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

local prefix = “I think”local postfix = “(I'm joking)”local str= lualist.join(tbl, ' ', prefix, postfix)print(str) ---> “I think Danny Square is a genius (I'm joking)”

Syntax:lualist.filter(lst, funzBool)

Description:Every time you need to filter elements from a table this fuction provide a good flexibility. Providethe table “lst” you need to filter and the “funzBool” function used as test for the filter.The function returns all the elements in “lst” satisfying the boolean function “funzBool”. Thisfunction receives as argument the current item of the list and return 1 if you choose the item or 0 ifyou discard it.

Examples:

Syntax:lualist.merge(lst1 [,lst2 ...])

Description:This function merge the elements of several lists in one list. In case of elements with same nameevery new insertion overwrite the previous value.

Examples:

Syntax:lualist.erase_n(lst, idx)

Description:This function delete the “idx” element from the list “lst” moving all the following items back inorder to fill the gap. In case of huge lists this might be slow.

Examples:

Syntax:lualist.asCdf(list, stringfmt)

Description:Returns a string applying the CDF (Comma Delimited File) standard created from the fields of theprovided list “lst”.“stringfmt” is a sequence of characters required for the complete definition of the format.(s=stringa, i=int, f=float)This function is suitable every time you need to export data to a SpreedSheet.

Examples:

local str = lualist.asCdf({1,2,3}, "isi"} --->: << 1, "2", 3 >>

Page 35: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Filenames Functions

Syntax:catpath(path, name) -> fullname

Description:This function concat “path” and “name”, adding the backslash if necessary.

Examples:

function PrintFile(cls, path, file)local nomef = catpath(path, file)local fn = fopen(nomef, "r") if not fn then alert("File " .. nomef .. " not found.") return endwhile(1) do

local s = fn:readLine()if not s then break endprint(s)

endfclose(fn)

end

Syntax:FnGetPath(fullName) -> path

Description:Given a complete filename this function returns just the path part.

Examples:

function ShowSystemTemporaryFolder()local fname = tempfilename{} local npath = FnGetPath(fname)print(npath)

end

Syntax:FnGetName(fullName) -> name

Description:Given a complete filename this function returns just the file name part (with extension)

Examples:

local fnamewithoutext = FnChangeExt(FnGetName(completepath), "")

Page 36: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Syntax:FnGetExt(filename) -> ext

Description:Given a complete filename this function returns just the file extension.

Examples:

function ProcessDwgs(lst)for i, fname in lst do

local ext = FnGetExt( fname )if strupr(ext) == '.DWG' then setvar('sdi', 1)dwgopen( fname )

-- do something...

command {"_QSAVE"} end

endend

Syntax:FnChangeExt(fileName, newExt)

Description:This function change the extension of the passed file “fileName”, adding the new value “newExt”.

“fileName” is the filaname.“newExt” is the new extension (with the dot). If not provided the previous extension will be deleted

Examples:

local fnamewithoutext = FnChangeExt(FnGetName(completepath), "")

Syntax:FilePathSearch(name, pathList)

Description:Searches the file “name” into the list of folders provided with “pathList”. “pathList” contains alist o f directories paths separated by “;”.If the function is successful returns the complete pathname, otherwise a nil value will be returnedto the user.

Examples:

print(FilePathSearch('notepad.exe', getenv('PATH')))---> “c:\windows\notepad.exe”

Syntax:FileCopy(srcname, dstname)

Page 37: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Description:Calling this function a copy of “srcname” will be performed on “dstname”.

Examples:

Syntax:luafullpath(basename)

Description:Returns a filename composed by the path of the LUA interpreter followed by the provided“basename”.

Examples:

Syntax:tempfilename(tabOptions)

Description:Create a temporary unique file name. Some options are available:

Options:

Field Name Type Description

dir string Directory (temporary system folder ifomitted)

ext string Extension of the new file (default .tmp)

make point Create the file. Otherwise just the filename would be returned.

name string Fixed file name optional.

Examples:

Page 38: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Files Functions

Syntax:FileExists(filename) -> bool

Description:This function checks whether a file “filename” exists. It returns 1 if it exists, and nil otherwise.

Examples:

function BatchSaveAsDWG()local sdi = getvar('sdi')setvar('sdi', 1)local files = FileMultiSel()local cnt = 0if (not files) then return endfor i, fname in files do

local dwg = FnChangeExt( fname , ".dwg")if (not FileExists(dwg)) thenlocal ext = FnGetExt( fname )-- process only DXFif strupr(ext) == '.DXF' then command('_open', fname )-- add your code here

command ("_saveas" , "2000" , "") cnt = cnt + 1

endend

endalert(format(" %d files successfully converted" , cnt ))setvar('sdi', sdi)end

Syntax:FileIsDirectory(filename) -> bool

Description:Returns 1 if filename is a “directory”, nil otherwise.

Examples:

Syntax:GetFileAttributes(name)

Description:The GetFileAttributes function retrieves attributes for a specified file or directory. Returns a stringwith the values:

Page 39: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Value Type

A archive

R read only

S system file

D directory

Examples:

function IsThisDrawingReadOnly()local DwgName=getvar("dwgname")local DwgPrefix=getvar("dwgprefix") local dwgFull=catpath(DwgPrefix,DwgName)local attrib=GetFileAttributes(dwgFull)if (wcmatch(attrib,"*R*")) then

print("file readonly")end

end

Syntax:SetFileAttributes(name, attrString)

Description:

The SetFileAttributes function sets a file's attributes. “name” is the complete filename, and“attrString” is a string with the attributes to set. Every attribute has to be prefixed with “+” if youneed to add it, “-” if you want remuve it (ie “+A-R”) .

Examples:

Syntax:fopen(fileName, fileOpenMode) -> fileObj

Description:The fopen function opens the file specified by “fileName”. fileOpenMode defines the way you openthe file.

symbol mode

'w' write

'r' read

'a' append

Examples:

Page 40: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

function DbgSerializeOnDesktop(tbl)local fname = tempfilename({dir = 'C:\\Documents and Settings\\Administrator\\Desktop',

ext='.txt'})local fn = fopen(fname, 'w')fn:serialize(tbl, 'yourdata')fn:close()

end

Syntax:popen(command, mode) -> fileObj

Description:The popen() function executes the command specified by the string “command”. It creates a pipebetween the calling program and the executed command, and returns a pointer to a stream that canbe used to either read from or write to the pipe. Like the “C Language”.

If “mode” is 'r', reading from the file you can read the program's output.

Examples:local fn = popen('dir /s /b', 'r')local str = fn:readLine() -- legge la prima linea dell'output di dirfn:close()

Syntax:<file>:close()

Description:Closes the <file> object.

Examples:

Syntax:<file>:seek(pos)

Description:Sets the position (in “pos”) for the next read/write operation within a file opened using the “fopen”method.

Examples:

Syntax:<file>:puts(s)

Description:The function “puts” may be used to copy a string to the <file> object, its single parameter is thestring. Remeber that puts() doesn't write a new-line character to the file after it has written thestring.

Page 41: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Examples:

Syntax:<file>:readLine()

Description:Read a line from the ASCII file <file> and returns the string.The “readLine()” method returns the first line the first time it is called, and then the second line thesecond time it is called, and so on, until the end of the file is reached when it returns a nil value.

Examples:

Syntax:<file>:serialize(table, name)

Description:This is a very powerful fuction. Save the table “table” into the variable “name” to the file <file>using the LUA syntax so that you can read the file using the “dofile” function. This function alsoattempts to indent correctly the structure.

Examples:

a = {1, 2};f:serialize(a, "var")---> writes "var={1,2}" on file.

function DbgSerializeOnDesktop(tbl)local fname = tempfilename({dir = 'C:\\Documents and Settings\\Administrator\\Desktop',

ext='.txt'})local fn = fopen(fname, 'w')fn:serialize(tbl, 'yourdata')fn:close()

end

Syntax:<file>:eof()

Description:Returns 1 if the file is finished, nil otherwise.

Examples:

Page 42: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Directories Functions

Syntax:getcwd()

Description:Returns the name of the current directory.

Examples:

Syntax:mkdir(nomeDir)

Description:Creates a new folder. Nested folders are allowed.

Examples:

Syntax:chdir(nomeDir)

Description:Changes the current directory.

Examples:NewDirIterator(pattern)

Description:Creates a new <dirIterator> object. You may use this object to iterate through a directory tree.

Examples:

local x = NewDirIterator('c:\\temp\\*')while(x:next()) do print x:fullName() end

Syntax:<dirIterator>:next()

Description:Move ahead (next file) the iterator's pointer.

Examples:

Syntax:<dirIterator>:getFullName()

Description:Returns the complete filename of the current file.

Page 43: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Examples:

Syntax:<dirIterator>:getName()

Description:Returns the filename (without path) of the current file.

Examples:

Syntax:<dirIterator>:isDir()

Description:Returns 1 if the current file is a directory.

Examples:

Syntax:<dirIterator>:close()

Description:Destroy the <dirIterator> object.

Examples:

Page 44: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Windows Functions

Syntax:alert(msg1 [, msg2...])

Descriptions:Shows a message box with the provided messages (separated by spaces).

Examples:

Syntax:FileMultiSel()

Description:Shows a dialog box requiring the user to select one or more files. “Drag&Drop” is supported,returns the list containing filenames as strings. Return nil in case of errors.

Examples:

Syntax:GetFileNameIn(options)

Description:This command emulates the standard Windows file selection dialog box. Requires the user to selectan existing file. Returns the complete filename string or nil.

Options table format:

Nome Campo Tipo Desc

dir string default folder

filter string list of couples separated by'/' with pattern (ie 'Allfiles/*.*/Drawings/*.dwg///'

name string default file name

title string dialog box caption

Examples:

Syntax:GetFileNameOut(options)

Description:This command emulates the standard Windows file selection dialog box. Requires the user to selecta file. Returns the complete filename string or nil. “GetFileNameOut” asks you to create (confirmoverwrite) a new file. Returns the complete filename or nil

Page 45: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Nome Campo Tipo Desc

dir string default folder

filter string list of couples separated by'/' with pattern (ie 'Allfiles/*.*/Drawings/*.dwg///'

name string default file name

title string dialog box caption

Examples:

Syntax:BrowseForFolder()

Description:Use this function every time you need to select a folder. Returns the selected name (string) or nil.

Examples:

Syntax:MessageBox(options, text, title)

Description:This function shows the standard Windows message box. The returned value depends on theconfiguration:

Button Value

OK/YES 1

NO 0

CANCEL nil

“options” is a string composed by ono er more characters. Each character activates a differentconfiguration of buttons and icons.

Character Mode

a Ok button

b Ok/Cancel buttons

c Yes/No buttons

d Yes/No/Cancel buttons

e Retry/Cancel button

2 default2

3 default3

i info icon

Page 46: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Character Mode

j warning icon

k question icon

stop icon

Examples:

local yes_or_not = MessageBox('ck', “Delete file”, “Confirm”)

Syntax:InputBox(options)

Description:This is a simple dialog waiting for the user entering text.

Options table format:

Field Name Type Description

prompt string user prompt above the edit box

text string Default text into the edit box

pwd integer if 1 the standard password edit box will beused

title string dialog box caption

maxlen integer maximum lenght for the input string

Examples:

Syntax:dbgPrint(s1 [, s2 ...])

Description:This function uses the “print” syntax, but the output is streamed on the debug console (iedebugview)

Examples:

Syntax:IsConsole()

Description:Returns 1 if the current script is running in a console window.

Examples:

Syntax:WinExec(options)

Page 47: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Description:Runs an external program. Similar to “execute”, this function offers more options

Options table format:

Field name Type Description

cmd string the command that need to be executed

dir string the current process folder

wait integer if 1 wait for the end of the command.

showMode integer Window mode (showwindow)(0=hidden, 1=normal, 3=maximize,6=minimize)

Examples:

Syntax:ShellExecute(options)

Description:You can use the ShellExecute() function to start the application associated with a given documentextension without knowing the name of the associated application. For example, you could start thePaintbrush program by passing the filename ARCADE.BMP to the ShellExecute() function.

Options table format:

Field name Type Description

file string File to open

verb string Action: open=apen the file, print=printthe file, ...

dir string the current process folder (optional)

hidden bool Se 1, the program will start in hiddenmode (optional default=0)

minimized bool Se 1, the program will start iconized.

Examples:

Page 48: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Date

Syntax:DateToJulian(anno, mese, giorno)DateToJulian{y=anno, m=mese, d=giorno}

Description:Converts a calendar date to a Julian day number.The Julian day numbers used in this function are sequential starting with 1 on January 1 in theyear 1. Note that this is not the same convention used in the Julian day system used by astronomers.

Examples:

Syntax:Julian2Date(juldate)

Description:Translate the Julian string “juldate” to a (y, m, d) format. Returns a table where:

Symbol Value

y Year

m Month

d Day

Examples:

Syntax:Julian2Dow(juldate)

Description:Returns the day of the week (0 = mon, .., 6 = sun) from the date “juldate”.

Examples:

Syntax:DateToday()

Description:Returns the current date.

Examples:

Page 49: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Bit - Bytes

Syntax:bitxor(a, b [, ...])

Description:Performs an XOR between the arguments.

Examples:

Syntax:crc32(str)

Description:Calculates the CRC32 from the string “str”

Examples:

Page 50: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Mathematical functions

Have a look at the mathematical functions explained in the standard LUA user guide

Syntax:modf(num)

Description:

The modf() function decomposes the parameter value into integral and fractional parts. Each parthas the same sign as the parameter. This function returns 2 values.

Examples:

local integral, fractional = modf(1.23) ---> ora integral = 1 e fractional = 0.23

Syntax:round(num, numDigits)

Description:Returns a number rounded to a specified number of decimal places. “numDigits” is a numberindicating how many places to the right of the decimal are included in the rounding.

Examples:

print(round(2.15,1)) -- scrive 2.2print(round(2.149,1)) -- scrive 2.2print(round(-1.475, 2)) -- scrive -1.48

Page 51: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Various Functions

Syntax:getenv(nameVar)

Description:The getenv() function obtains the current value of the environment variable “nameVar”. Returnsthe string value.

Examples:

Syntax:dofile(fileName)

Description:Loads and executes an external LUA files.

Examples:

Syntax:dofilemulti(pattern)

Description:Executes the “dofile” command for every LUA file matching the pattern. (ie 'c:\\temp\\*.lua')

Examples:

Syntax:require(file1, ...)

Description:Loads (just once) and executes the files “file1, file2, ..., filen”. For each element it sets“included_files[file] = 1” .

Examples:

Syntax:loadlib(filename)

Description:Load the DLL module file “filename”.

Examples:

Syntax:globals() -> tab

Description:

Page 52: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Returns a LUA table with all the global symbols.

Examples:

Syntax:gc()

Description:Invoke the garbage collector.

Examples:

Syntax:assert(expression)

Description:Shows a message if the expression is false (see LUA user guide).

Examples:

Syntax:tagname(var)

Description:Returns the name of the type with “tag = <var>” or the class name if “var” is an object.

Examples:

Syntax:delay(nSeconds)

Description:"delay" is a function that suspends the current application for the specified duration <nSeconds>(in seconds.)

Examples:

Page 53: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

TOP Parts Management

Part ObjectThis object allows you to work on the TOP part structure.

Syntax:top_ptop() -> part

Description:Returns the TOP part (the root of the tree) of the current drawing.

Examples:

top_ptop():setAttr(“code”, “2”)local top = top_ptop()

Syntax:top_pcur() -> part

Description:Returns the current part of the current drawing.

Examples:

local newprtdad = top_prtselect() or top_pcur()

This piece of code return a user selected part or the current part.

Syntax:<part>:getParent() -> part

Description:Returns the “part” parent part.

Examples:

function GetDwgParts(attribs)local index = {}top_ptop():foreach(function(prt)

local item = {}item.attributi = {} for i=1, getn(%attribs) doitem.attributi[%attribs[i]] = prt:getAttr(%attribs[i])

endif prt ~= prt:getParent() thenitem.DadHandle = prt:getParent()

end%index[prt] = item

end) return index

end

Page 54: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Return the complete part list with attributes

Syntax:<part>:setParent(newParent)

Description:This function sets a new parent “newParent” part for the “part” (aggregate)

Examples:

Syntax:<part>:getName()

Description:Returns the part name as string.

Examples:

function PrtGetChildrenByKey(prt)PrtAssert(prt)local children = {} prt:foreach1(function (child)

local prtname = child:getName()tinsert(%children, {prtname, child})

end)return children

end

Syntax:<part>:setName(name)

Description:This function sets the part name. “name” is the string with the new name.

Examples:

function RenameAllParts(prefix)local tmp = {}tmp.i = 1top_ptop():foreach(function(prt)prt:setName(prefix .. tostring(i))%tmp.i = %tmp.i + 1end)end

Syntax:<part>:getAttr(AttributeName)

Description:

Page 55: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

This function reads the part attribute value “AttributeName” and returns the string with the valueor nil if the provided attribute is undefined.

Examples:

local code = prt:getAttr('CODE')local weight = tonumber(prt:getAttr('WEIGHT') or “0”)

function PrtGetEntities(prt) assert(prt)local layer = prt:getAttr("$lay") local ss = selset.filter {{8, layer}} return ss

end

This function returns a selection set containing the part entities.

Syntax:<part>:setAttr( AttributeName , AttributeValue )

Description:This function set a new attribut value for the part. If the attribute is already present the currentvalue will be overwritten. “AttributeName” is the field, “AttributeValue” is the value.

Examples:

function PrtSetAttribs(prt, lista)for key, val in lista do

if(val) thenprt:setAttr(key, val)

endend

end

This function sets several attributes at once

Syntax:<part>:delAttr( AttributeName )

Description:This function delete the “AttributeName” attribute from the parts attributes.

Examples:

function DeleteAllAttributes(badattribute)top_ptop():foreach(function(prt)if (prt:getName() == % badattribute ) thenprt:delAttr(badattribute)

end

Page 56: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

end)end

Syntax:<part>:activate()

Description:This function change the current part, activating the part “part”

Examples:

function GetEntsFrom(ent)local ent = ent:entnext()local ss = selset.new()while ent do

ss:add(ent)ent = ent:entnext()

endreturn ssend

function MovePrt(prt, from, to, activate) local prtcurif activate then

prtcur = top_pcur()prt:activate()

endlocal ssall = selset.new()prt:foreach(function(prt)

local ss = PrtGetEntities(prt)if ss thenlocal len = ss:count()for i=0, len do%ssall:add(ss:item(i))

endss:free()

endend)if ssall and ssall:count() > 0 then

command({"_MOVE", ssall, "", from, to})endssall:free()if prtcur then

prtcur:activate()end

end

Syntax:

Page 57: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

<part>:new(name)

Description:This function creates a new part as child of “part”. The “name” parameter is the name for thepart to be created.

Examples:

local prt = prt:new('New part')prt:activate()

function GetEntsFrom(ent)local ent = ent:entnext()local ss = selset.new()while ent do

ss:add(ent)ent = ent:entnext()

endreturn ssend

Syntax:<part>:aggr(selset) <NOT COMPLETE>

Description:This function aggregates to the “part” part all the entities provided with the selection set “selset”.This version requires a selection set as parameter. Returns 1 or nil.

Examples:

function GetEntsFrom(ent)local ent = ent:entnext()local ss = selset.new()while ent do

ss:add(ent)ent = ent:entnext()

endreturn ssend

function LoadPartEx(prtdad, options)--alert(options)local ent = entlast()local prt = prtdad:load({file = options.file, point = options.point, angle = options.angle})local ss = GetEntsFrom(ent) if ss and ss:count() > 0 then

prt:aggr(ss)ss:free()

endreturn prt

Page 58: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

end

Syntax:<part>:explode()

Description:Explodes the “part”. No confirm is required.

Examples:

if FileExists(myfile) then local prt = prt:load({file = myfile, point = Point(0,0,0), angle = 0.0}) prt:explode() end

Syntax:<part>:erase()

Description:Delete the part and all children. No confirm is required.

Examples:

function DeleteParts(badname)top_ptop():foreach(function(prt)if (prt:getName() == %badname) thenprt:erase()

endend)end

-- This function deletes all parts with “badname”

Syntax:<part>:isChildOf(part2)

Description:Returns 1 if “part2” is child of “part”.

Examples:

local array = {}local selectedprt = top_prtselect()top_foreachpart(top_ptop(),function (prt)if prt:isChildOf(selectedprt) thentinsert(%array, prt)end

Page 59: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Syntax:<part>:foreach(func)

Description:This is a very powerful function. “foreach” iterates all parts at every level and calls the functionfunc on every part (as parameter of the function itself).If the function returns “True” (not nil) the iteration stops and foreach returns the value.

Examples:

local prtfound = top_ptop:foreach(function(prt)if (prt:getAttr(“weight”)==”2”) thenreturn prtendend)

-- This example looks for a part with “weight = 2“

function PartsFilter(root, field, value)local prts = {}root:foreach(function(prt)

if prt:getAttr(%field) == %value thentinsert(%prts, prt)

end end)return prts

end

-- this example filters parts by attributes values

Syntax:<part>:foreach1(func)

Description:Very similar to the “foreach” function. “foreach1” iterates all parts at the firs level and calls thefunction func on every part (as parameter of the function itself).If the function returns “True” (not nil) the iteration stops and foreach returns the value.

Examples:

function CalculatePower(server)local power = {}power.value = 0server:foreach1(function(client) client:activate()local pow = client:getAttr("power")%power.value = %power.value + pow;

end)

Page 60: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

return power.valueend

Syntax:<part>:find(name)

Description:Looks for a part, children of “part”, with the name “name”. If there are more then one part withthe same name, the function returns just the first match.

Examples:

local cart = top_ptop():find(“BOM”)

This example verify whether the part “BOM” exists or not.

Syntax:<part>:load(params)

Description:Loads an external part. The parts structure already present into the loaded file will be inserted aschild of “part”.

“params” is a table with the following format:

Name Type Description

file string name of the file to be loaded

opendir string base folder

angle number rotation angle. If omitted the functionasks the user. Decimal degree.

point point insertion point. If omitted thefunction asks the user.

Examples:

function GetEntsFrom(ent)local ent = ent:entnext()local ss = selset.new()while ent do

ss:add(ent)ent = ent:entnext()

endreturn ssend

function CaricaParteEx(prtdad, options)local ent = entlast()

Page 61: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

local prt = prtdad:load({file = options.file, point = options.point, angle = options.angle})local ss = GetEntsFrom(ent) if ss and ss:count() > 0 then

prt:aggr(ss)ss:free()

endreturn prt

end

if FileExists(dwgfile) then local newprt = prt:load({file = dwgfile, point = Point(0,0,0), angle = 0.0}) newprt:explode()

end

Syntax:<part>:save(params)

Description:Exports the selected part as new drawing where “part” is the new TOP part.

“params” is a LUA table with the following format:

Name Type Description

file string name of the newly created file. If missingasks the user

subprt 0 or 1 if 1 (default) save all the childrent, if 0just the part.

opendir string base folder for the “save” dialog box

Examples:

function TopPrtPrtCopy(prt)local tempName = tempfilename{name="partclp.dwg"}prt = prt or top_prtselect()if (not prt) then return end prt:save{file = tempName, subprt = 1}

end

function ExportAndReload(prt)local tempName = tempfilename{name="partclp.dwg"}prt:save({file = tempName , subprt = 0})prt:erase()local newprt = top_ptop():load({file = tempName })return newprt

end

Page 62: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Syntax:<part>::setBlockAttributes(entBlock)

Description:Sets the AutoCAD block Attributes cloning the “part” attributes.

Examples:

Page 63: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

PrtArray Object

The “PrtArray” object is a container for “part” objects

Syntax:NewPrtArray()

Description:Create a new empty “PrtArray”

Examples:

Syntax:<prtArray>:add(prt [, children])

Description:Append the part “prt” to the array. If “children = 1” all children will be queued.

Examples:

Syntax:<prtArray>:count()

Description:Returns the number of parts into the “PrtArray”.

Examples:

local pa = FunctionReturningArray() local len = pa:count()if len == 1 then

local prt = pa:getAt(0) or top_pcur() print(prt:getName())

end

Syntax:<prtArray>:getAt(index)

Description:Returns the part at the “index” position of the array.

Examples:

function TopPrtPrtCopyArray(pa)

Page 64: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

local len = pa:count()if (len == 1) then

TopPrtPrtCopy(pa:getAt(0))else

local prt = top_ptop():new('copyBuffer')local fathers = {}for i=0,len-1 do

local p = pa:getAt(i)padri[p] = p:getParent()p:setParent(prt)

endTopPrtPrtCopy(prt)for prt, father in fathers doprint("Setparent",prt," in ", father , "\n")

prt:setParent( father )end prt:erase()

endend

Page 65: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Global Functions

Syntax:top_prtfroment(ent)

Description:Returns the “part” containing the “ent” entity. If the entity doesn't belong to any part it returns nil.

Examples:

function aggregate()local s = selset.usersel()if (s == nil) then return endlocal e = entsel("Select part or press ENTER for the lis")local prtif (e == nil) then

prt = top_prtselect()elseif (e ~= nil) then

prt = top_prtfroment(e)endif (prt == nil) then return endprt:aggr(s)top_updspotlight()

end

Syntax:top_prtselect() -> prt

Description:Shows a dialog with the current drawing parts tree and ask the user to select just one part from thertree. Returns the selected part or nil.

Examples:

function TopPrtClipboardfile()return tempfilename{name="partclp.dwg"}

end

function TopPrtPrtCopy(prt)local tempName = TopPrtClipboardfile()prt = prt or top_prtselect()if (not prt) then return end prt:save{file = tempName, subprt = 1}

end

This function provides “Part Copy” functionalities.

Syntax:top_updcart()

Page 66: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

Description:Update the attributes into the drawing “cartiglio”

Examples:

Syntax:top_updtab()

Description:Update the attributes inot the BOM.

Examples:

Syntax:top_spotlight(mode)

Description:Sets the “spotlights” mode by the string “mode” provided as parameter.Mode can be “ON”, “OFF”, “FIGLI”, “TEMP”. Temp doesn't save the configuration.

Examples:

local old = top_spotlight(“OFF+TEMP”)-- turn spotlights offtop_spotlight(old)

Syntax:top_updspotlight()

Description:Iterates every entity in model space and update the “spotlight” color.

Examples:

function aggregate()local s = selset.usersel()if (s == nil) then return endlocal e = entsel("Select part or press ENTER for the lis")local prtif (e == nil) then

prt = top_prtselect()elseif (e ~= nil) then

prt = top_prtfroment(e)endif (prt == nil) then return endprt:aggr(s)top_updspotlight()

end

Syntax:

Page 67: AutoCAD LUA Extension - QS Informaticawin.qsinformatica.it/white_papers/manuals/AutoCAD_LuaSDK.pdf · Syntax is very similar to the counterpart AutoLisp function. Examples: ... entity

top_prtfullpath(baseName)

Description:Returns a complete filename from the TOP folder.

Examples:

LUA>print(prtfullpath('a.txt'))--->c:\programmi\qs\top_prt\a.txt

Syntax:TopDlgDist(options)

Description:Runs the BOM dialog box.

“options “ is a LUA table with the following parameters:

Name Type Description

type Table Type list (strings) to showinto the “combobox1”

filter Table Filters list to show into the“comboBox2”

Examples:

TopDlgDist{type={'Basic BOM'}, filter={'All parts'}}