% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/dt-copy-semantics.R
\name{maybe_copy_dt}
\alias{maybe_copy_dt}
\title{Return a data.table by reference or by value}
\usage{
maybe_copy_dt(x)
}
\arguments{
\item{x}{A \code{data.table} or \code{data.frame}.}
}
\value{
A \code{data.table}. Whether the return value aliases the input depends on
the semantics:
\itemize{
\item \code{"reference"}: input is mutated in place, aliasing guaranteed if
\code{x} is already a \code{data.table}.
\item \code{"value"}: a fresh copy is returned, independent of the input.
}
}
\description{
\code{\link[=maybe_copy_dt]{maybe_copy_dt()}} returns its input as a \code{data.table}, with behaviour
controlled by the global copy semantics option \code{\link[=dt_copy_semantics]{dt_copy_semantics()}}.
}
\details{
\itemize{
\item If the semantics are \code{"reference"} (default):
\itemize{
\item If \code{x} is already a \code{data.table}, it is returned unchanged. Aliasing
holds, so mutations with \verb{:=} will affect both input and output.
\item If \code{x} is a \code{data.frame}, it is converted to a \code{data.table} in place
via \code{\link[data.table:setDT]{data.table::setDT()}}, mutating the caller’s object. The returned
object is a \code{data.table} with the same contents. For efficiency, the
column vectors are reused without a deep copy.
}
\item If the semantics are \code{"value"}:
\itemize{
\item \code{x} is converted to a \code{data.table} (if necessary) and a deep copy is
returned. Mutating the result does not affect the input.
}
}
}
\examples{
# Default: reference semantics
df <- data.frame(a = 1:3)
out <- maybe_copy_dt(df)
data.table::is.data.table(df) # TRUE, converted in place

# Switch to value semantics
old <- set_dt_copy_semantics("value")
dt <- data.table::data.table(a = 1:3)
out2 <- maybe_copy_dt(dt)
out2[, b := 99L]
"b" \%in\% names(dt)  # FALSE, original unchanged

# Restore previous semantics
set_dt_copy_semantics(old)

}
\seealso{
\code{\link[=dt_copy_semantics]{dt_copy_semantics()}}, \code{\link[=set_dt_copy_semantics]{set_dt_copy_semantics()}}
}
